函数中的Python变量?

时间:2016-09-28 22:05:58

标签: 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: "))
    #...
    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)

ERROR:

 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

1 个答案:

答案 0 :(得分:2)

您需要在功能中加入global。外面什么也没做。

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()

但为什么需要全局变量?你打算在函数之外使用那些变量吗?仅当您需要修改函数范围之外的值时,才需要global

将代码重新格式化为:

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())

这不是通过全局变量传递信息,而是通过返回值传递信息。 There are hundreds of articles on why global variables are evil.

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

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


# MAIN
calculateValues(*getValues())

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

的更多信息
相关问题