Python 3.x 更改函数中的变量

Python 3.x 更改函数中的变量,python-3.x,Python 3.x,我需要从函数内部更改一个变量,该变量是一个参数 以下是我尝试过的代码: bar = False def someFunction(incoming_variable): incoming_variable = True someFunction(bar) print bar 当它应该返回True时,它返回False 如何更改变量?在您的示例中: bar is global variable existing oustide the scope of function someFu

我需要从函数内部更改一个变量,该变量是一个参数

以下是我尝试过的代码:

bar = False

def someFunction(incoming_variable):
    incoming_variable = True

someFunction(bar)

print bar
当它应该返回True时,它返回False

如何更改变量?

在您的示例中:

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)

  • 将条形图(
    False
    )的值分配给局部变量
    传入变量
  • 评估函数
如果希望简单地更改变量栏:

def someFunction(incoming_variable):
    bar= incoming_variable
在您的示例中:

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)

  • 将条形图(
    False
    )的值分配给局部变量
    传入变量
  • 评估函数
如果希望简单地更改变量栏:

def someFunction(incoming_variable):
    bar= incoming_variable

你不能。赋值将本地名称重新绑定到一个全新的值,使调用范围中的旧值保持不变

一个可能的解决办法是突变不会重新绑定。传入列表而不是布尔值,并修改其元素

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
而且,总有
全局的

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
,因此它们可能不合适。取决于你想做什么。

你不能。赋值将本地名称重新绑定到一个全新的值,使调用范围中的旧值保持不变

一个可能的解决办法是突变不会重新绑定。传入列表而不是布尔值,并修改其元素

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
而且,总有
全局的

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
,因此它们可能不合适。取决于你想做什么