2016-09-28 125 views
1

我有一个关于变量的小问题。我的主要语言是Java语言(我学习Python)的话,我有一个函数调用变量的问题,它不会刷新其新的价值:函数中的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() 

我试图把它写不全球,试图用自我字,但它不起作用。 (使用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 
+1

刻录*全局e1x,e1y,e1c,e2x,e2y,e2c,altx,alty,x,y *。你并不是真的想要使用全局变量。你也可以在类方法中使用'self',其中self表示方法将被调用的实例。如果你想使用这个逻辑,那么实际上不仅仅是函数创建一个类。 –

+0

“不起作用”不是问题描述。你有错误吗?如果是这样,完整的追溯是什么?它表现出意外吗?如果是这样,请描述预期的和实际的行为。 –

+0

当我尝试在'calculateValues()'上使用它时,Python说“e1x没有定义”,但是我在顶部声明并初始化了实际返回这些值的函数@SvenMarnach –

回答

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.

+0

是的,我会用在calculateValues() –

+0

@AlfonsoIzaguirreMartínez不,你没有。 'calculateValues()'应该调用'getValues()'并使用返回值。或者,您可以将'getValues()'的结果传递给'calculateValues()'。全局变量是邪恶的。 –