Python的参数传递对所有对象都是一样的-传递原始对象(不是“副本”,不是“引用”,不是“指针”-传递的是对象本身),而不管对象的类型,是否可变等等。然后这些对象作为局部变量绑定到其匹配参数的名称上。在
您观察到的差异实际上是完全不同操作之间的差异的结果:重新绑定(本地)名称和更改对象。在
由于参数是局部变量(实际上是局部名称),在函数体中重新绑定参数只会使该名称指向另一个对象,不会影响原始参数(除了减少引用计数器)。很明显,这在函数本身之外没有任何影响。在
现在当你改变你的一个参数,因为你正在处理你传递给函数的对象,这些变化很明显,在函数之外是可见的。在
这里:def external_1(instance_var, instance_list, instance_str, instance_tuple, instance_dict):
# this one rebinds the local name `instance_var`
# to a new `int` object. Doesn't affect the object
# previously bound to `instance_var`
instance_var += 1
# those three statement mutate `instance_list`,
# so the effect is visible outside the function
del instance_list[0]
del instance_list[0]
instance_list[0] = 15
# this one rebinds the local name `instance_str`
# to the literal string "Bar". Same as for `instance_var`
instance_str = "Bar"
# this one creates a list from `instance_tuple`,
# mutate this list, and discard it. IOW it eats a
# couple processor cycles for nothing.
list(instance_tuple)[0] = 15
# and this one mutates `instance_dict` so the
# effect is visible outside the function
instance_dict.update({"one": 15})
在这里:
^{pr2}$