2014-04-11 64 views
0

我需要從函數內部更改變量,並將變量作爲參數。從函數中更改變量

這裏是我試過的代碼:

bar = False 

def someFunction(incoming_variable): 
    incoming_variable = True 

someFunction(bar) 

print bar 

返回FALSE,當它應返回true。

如何獲取變量?

回答

3

你不能。賦值重新將本地名稱重新命名爲一個全新的值,使舊值在調用範圍內保持不變。

一種可能的解決方法是突變不會重新綁定。傳入一個列表而不是布爾值,並修改其元素。

bar = [False] 

def someFunction(incoming_variable): 
    incoming_variable[0] = True 

someFunction(bar) 

print bar[0] 

您也可以通過這種方式改變類屬性。

class Thing: 
    def __init__(self): 
     self.value = None 

bar = Thing() 
bar.value = False 

def someFunction(incoming_variable): 
    incoming_variable.value = True 

someFunction(bar) 

print bar.value 

而且,總是有global

bar = False 
def someFunction(): 
    global bar 
    bar = True 
someFunction() 
print bar 

以及自修改類。

class Widget: 
    def __init__(self): 
     self.bar = False 
    def someFunction(self): 
     self.bar = True 

w = Widget() 
w.someFunction() 
print w.bar 

但隨着最後兩個,你輸了不同的參數傳遞給someFunction的能力,所以他們可能並不適用。取決於你想要做什麼。

1

在您的例子:

bar is global variable existing oustide the scope of function someFunction 

Whereas incoming_variable is local variable residing only in the scope of function someFunction 

調用someFunction(bar)

  • assings條(False)的值,局部變量incoming_variable
  • 計算函數

,如果你想要變量欄簡單地改變:

def someFunction(incoming_variable): 
    bar= incoming_variable