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}$

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值