saj*_*ith 6 python reference list
任何人都可以向我解释为什么下面的两个函数a和b行为不同.函数在本地a更改names并b更改实际对象.
我在哪里可以找到这种行为的正确文档?
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
Run Code Online (Sandbox Code Playgroud)
输出:
before calling any function ['Fred', 'George']
after calling a ['Fred', 'George']
after calling b ['Fred', 'George', 'Bill']
Run Code Online (Sandbox Code Playgroud)
分配给函数内部的参数不会影响传递的参数.它只使局部变量引用新对象.
同时,list.append就地修改列表.
如果要更改函数内的列表,可以使用切片赋值:
def a(names):
names[:] = ['Fred', 'George', 'Bill']
Run Code Online (Sandbox Code Playgroud)
函数a创建一个新的局部变量names并将列表分配['Fred', 'George', 'Bill']给它。因此,正如您已经发现的那样,这现在是与global 不同的变量。first_names
您可以在此处阅读有关修改函数内列表的信息。
使函数的a行为与函数相同的一种方法b是使函数成为修饰符:
def a(names):
names += ['Bill']
Run Code Online (Sandbox Code Playgroud)
或者你可以创建一个纯函数:
def c(names):
new_list = names + ['Bill']
return new_list
Run Code Online (Sandbox Code Playgroud)
并称其为:
first_names = c(first_names)
print first_names
# ['Fred', 'George', 'Bill']
Run Code Online (Sandbox Code Playgroud)
纯函数意味着它不会改变程序的状态,即它没有任何副作用,例如更改全局变量。