[英]How can we simulate pass by reference in python?
Let's say we have a function foo()
假设我们有一个函数
foo()
def foo():
foo.a = 2
foo.a = 1
foo()
>> foo.a
>> 2
Is this pythonic or should I wrap the variable in mutable objects such as a list? 这是pythonic还是应该将变量包装在可变对象(例如列表)中?
Eg: 例如:
a = [1]
def foo(a):
a[0] = 2
foo()
>> a
>> 2
Since you "want to mutate the variable so that the changes are effected in global scope as well" use the global
keyword to tell your function that the name a
is a global variable. 由于您“希望对变量进行突变,以使更改也能在全局范围内生效”,因此请使用
global
关键字来告诉函数名称a
是全局变量。 This means that any assignment to a
inside of your function affects the global scope. 这意味着,任何分配到
a
你的函数内影响全球范围内。 Without the global
declaration assignment to a
in your function would create a new local variable. 如果没有
global
宣言分配到a
在你的函数将创建一个新的局部变量。
>>> a = 0
>>> def foo():
... global a
... a = 1
...
>>> foo()
>>> a
1
Use a class (maybe a bit overkill): 使用一堂课(也许有点矫kill过正):
class Foo:
def __init__(self):
self.a = 0
def bar(f):
f.a = 2
foo = Foo()
foo.a = 1
bar(foo)
print(foo.a)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.