[英]Python confusing function reference
Can anyone explain to me why the two functions below a
and b
are behaving differently. 任何人都可以向我解释为什么
a
和b
下面的两个函数表现不同。 Function a
changes names
locally and b
changes the actual object. 函数
a
在本地更改names
, b
更改实际对象。
Where can I find the correct documentation for this behavior? 我在哪里可以找到这种行为的正确文档?
def a(names):
names = ['Fred', 'George', 'Bill']
def b(names):
names.append('Bill')
first_names = ['Fred', 'George']
print "before calling any function",first_names
a(first_names)
print "after calling a",first_names
b(first_names)
print "after calling b",first_names
Output: 输出:
before calling any function ['Fred', 'George']
after calling a ['Fred', 'George']
after calling b ['Fred', 'George', 'Bill']
Assigning to parameter inside the function does not affect the argument passed. 分配给函数内部的参数不会影响传递的参数。 It only makes the local variable to reference new object.
它只使局部变量引用新对象。
While, list.append
modify the list in-place. 同时,
list.append
修改列表。
If you want to change the list inside function, you can use slice assignment: 如果要更改函数内的列表,可以使用切片赋值:
def a(names):
names[:] = ['Fred', 'George', 'Bill']
Function a
creates a new, local variable names
and assigns list ['Fred', 'George', 'Bill']
to it. 函数
a
创建一个新的本地变量names
并为其分配列表['Fred', 'George', 'Bill']
。 So this is now a different variable from the global first_names
, as you already found out. 所以现在这是与全局
first_names
不同的变量,正如您已经发现的那样。
You can read about modifying a list inside a function here . 您可以在此处阅读有关修改函数内的列表的信息 。
One way to make function a
behave the same as function b
is to make the function a modifier : 使函数
a
行为与函数b
相同的一种方法是使函数成为修饰符 :
def a(names):
names += ['Bill']
Or you could make a pure function: 或者你可以做一个纯粹的功能:
def c(names):
new_list = names + ['Bill']
return new_list
And call it: 并称之为:
first_names = c(first_names)
print first_names
# ['Fred', 'George', 'Bill']
A pure function means it doesn't change the state of the program, ie it doesn't have any side effects, like changing global variables. 纯函数意味着它不会改变程序的状态,即它没有任何副作用,比如改变全局变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.