函数中的Python变量?

函数中的Python变量?,python,python-3.x,Python,Python 3.x,我有一个关于变量的小问题。我的主要语言是Java(我正在学习Python),因此,调用函数中的变量时遇到问题,它不会刷新其新值: # Values global e1x, e1y, e1c, e2x, e2y, e2c, altx, alty, x, y def getValues(): print("Taking Ax + By = C:") e1x = float(input("Value of x in first equation: ")) #... i

我有一个关于变量的小问题。我的主要语言是Java(我正在学习Python),因此,调用函数中的变量时遇到问题,它不会刷新其新值:

# Values
global e1x, e1y, e1c, e2x, e2y, e2c, altx, alty, x, y

def getValues():
    print("Taking Ax + By = C:")
    e1x = float(input("Value of x in first equation: "))
    #...
    if(confirm()): # A function I ommited 'cause its irrelevant
        return e1x, e1y, e1c, e2x, e2y, e2c
    else:
        getValues()

def calculateValues():
    # Stuff with variables


# MAIN
getValues()
calculateValues()
我试着在没有全局的情况下写它,试着用self这个词,但是,它不起作用。(使用Python 3)

错误:

 Traceback (most recent call last):
   File "E002_GaussSeidel.py", line 41, in <module>
      calculateValues()
   File "E002_GaussSeidel.py", line 34, in calculateValues
      print(str(e1x))
 NameError: name 'e1x' is not defined
回溯(最近一次呼叫最后一次):
文件“E002_gausseidel.py”,第41行,在
calculateValues()
文件“E002_gausseidel.py”,第34行,在CalculateValue中
打印(str(e1x))
名称错误:未定义名称“e1x”

您需要将
全局
包含在您的功能中。在外面它什么也不做

def getValues():
    global e1x, e1y, e1c, e2x, e2y, e2c, altx, alty, x, y
    print("Taking Ax + By = C:")
    e1x = float(input("Value of x in first equation: "))
    #...
    if(confirm()): # A function I ommited 'cause its irrelevant
        return e1x, e1y, e1c, e2x, e2y, e2c
    else:
        getValues()

def calculateValues():
    # Stuff with variables


# MAIN
getValues()
calculateValues()
但是为什么需要全局变量呢?你打算在函数之外使用这些变量吗<代码>全局仅在需要修改函数范围之外的值时才是必需的

将代码重新格式化为:

def getValues():
    print("Taking Ax + By = C:")
    e1x = float(input("Value of x in first equation: "))
    #...
    if(confirm()): # A function I ommited 'cause its irrelevant
        return e1x, e1y, e1c, e2x, e2y, e2c
    else:
        getValues()

def calculateValues(values):
    # Stuff with variables


# MAIN
calculateValues(getValues())
它不是通过全局变量传递信息,而是通过返回值传递信息

保存返回的变量
e1x、e1y、e1c、e2x、e2y、e2c
。可以使用列表索引表示法访问它。如果要按变量名称引用变量,请使用:

#...
def calculateValues(e1x, e1y, e1c, e2x, e2y, e2c):
    # Stuff with variables


# MAIN
calculateValues(*getValues())

*foo
是列表解包符号。这是一个高级主题,但在您的情况下很有用。您可以阅读有关列表解包的更多信息

刻录全局e1x、e1y、e1c、e2x、e2y、e2c、altx、alty、x、y。你不是真的想用globals。您还可以在类方法中使用
self
,其中self引用将调用该方法的实例。如果你想使用这种逻辑,那么实际上创建一个类而不仅仅是函数。“它不工作”不是一个问题描述。你有错误吗?如果是这样,完整的回溯是什么?它的行为是否出人意料?如果是,请描述预期的和实际的行为。当我尝试在“calculateValues()”上使用它时,Python会说“e1x未定义”,但我在顶部声明并在实际返回这些值的函数上初始化了它@SvenMarnach@AlfonsoIzaguirreMartínez您应该将全局decl移动到
getValues()
的顶部。但是你不想使用全局变量,因为它们是邪恶的。@AlfonsoIzaguirreMartínez这应该包括在你的问题中,包括错误的完整回溯。你不能在Python中声明变量,函数定义之外的
global
也不能做任何事情。是的,我将使用in-calculateValues()@AlfonsoIzaguirreMartínez不,你不能
calculateValues()
应该调用
getValues()
并使用返回值。或者,您可以将
getValues()
的结果传递给
calculateValues()
。全局变量是邪恶的。