python self 值自动改变_Python,为什么传递和更改带有外部函数的类selfvariable用于操作iterable而不是变量...
Python的參數(shù)傳遞對(duì)所有對(duì)象都是一樣的-傳遞原始對(duì)象(不是“副本”,不是“引用”,不是“指針”-傳遞的是對(duì)象本身),而不管對(duì)象的類型,是否可變等等。然后這些對(duì)象作為局部變量綁定到其匹配參數(shù)的名稱上。在
您觀察到的差異實(shí)際上是完全不同操作之間的差異的結(jié)果:重新綁定(本地)名稱和更改對(duì)象。在
由于參數(shù)是局部變量(實(shí)際上是局部名稱),在函數(shù)體中重新綁定參數(shù)只會(huì)使該名稱指向另一個(gè)對(duì)象,不會(huì)影響原始參數(shù)(除了減少引用計(jì)數(shù)器)。很明顯,這在函數(shù)本身之外沒有任何影響。在
現(xiàn)在當(dāng)你改變你的一個(gè)參數(shù),因?yàn)槟阏谔幚砟銈鬟f給函數(shù)的對(duì)象,這些變化很明顯,在函數(shù)之外是可見的。在
這里: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}$
總結(jié)
以上是生活随笔為你收集整理的python self 值自动改变_Python,为什么传递和更改带有外部函数的类selfvariable用于操作iterable而不是变量...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HTML中form和div出现间隙以及页
- 下一篇: python实现简单的名字管理系统_py