2014-04-11 63 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