2016-09-28 110 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()'。全局變量是邪惡的。 –