python self 值自动改变_Python,为什么传递和更改带有外部函数的类selfvariable用于操作iterable而不是变量...
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}$
總結
以上是生活随笔為你收集整理的python self 值自动改变_Python,为什么传递和更改带有外部函数的类selfvariable用于操作iterable而不是变量...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HTML中form和div出现间隙以及页
- 下一篇: java将数字转化为类似10W+的字符串