python中两个赋值运算符有什么区别?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python中两个赋值运算符有什么区别?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2342字,纯文字阅读大概需要4分钟。
内容图文
![python中两个赋值运算符有什么区别?](/upload/InfoBanner/zyjiaocheng/786/de7b12fd541949b9a9d5f456b55aa10a.jpg)
参见英文答案 > When is “i += x” different from “i = i + x” in Python? 4个
In [38]: d = set(range(3))
In [39]: d
Out[39]: set([0, 1, 2])
In [40]: for i in d:
d -= set([2])
....:
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
/home/gridlex/workspace/HomeBackSites/nava_scripts/<ipython-input-40-b79926ab34ec> in <module>()
----> 1 for i in d:
2 d -= set([2])
3
RuntimeError: Set changed size during iteration
python中这两个赋值有什么区别?
1.d – = set([2])
2 d = d – set([2])
In [41]: d = set(range(3))
In [42]: for i in d:
d = d - set([2])
....:
In [43]: d
Out[43]: set([0, 1])
解决方法:
对于像整数这样的不可变类型,a – = b与a = a – b相同:它创建一个新值a – b,并重新绑定名称a以引用该新值而不是旧值.
但是对于像集合这样的可变类型,a – = b会更改a指向就地的值. (它还将a重新绑定到它已经提到的相同值,但这并不重要.)
查看此对象的最佳方法是查看对象的标识:
>>> s1 = set(range(3))
>>> s2 = s1
>>> s1, id(s1), s2, id(s2)
({0, 1, 2}, 4303749432, {0, 1, 2}, 4303749432)
>>> s1 -= {1}
>>> s1, id(s1), s2, id(s2)
({0, 2}, 4303749432, {0, 2}, 4303749432)
>>> s1 = s1 - {2}
>>> s1, id(s1), s2, id(s2)
({0}, 4303749664, {0, 2}, 4303749432)
请注意, – =使s1仍然引用与s2相同的集合,并更改该集合; – 离开s1指的是一个具有不同id的全新集合,并且不会影响s2.
在封面下,a = a – b大致*等于a = a .__ sub __(b),而a – = b等于a = a .__ isub __(b).除非没有__isub__方法,否则a – = b只使用__sub__.
__isub__更改值的事实,而__sub__返回一个新值,并不是由语言强制执行,但它对所有内置和stdlib类型都是正确的,并且对任何自定义类型都是如此.它在Emulating numeric types中的文档中描述:
These [
__ifoo__
] methods should attempt to do the operation in-place (modifying self) and return the result (which could be, but does not have to be, self). If a specific method is not defined, the augmented assignment falls back to the normal methods. For instance, to execute the statementx += y
, where x is an instance of a class that has an__iadd__()
method,x.__iadd__(y)
is called. If x is an instance of a class that does not define a__iadd__()
method,x.__add__(y)
andy.__radd__(x)
are considered, as with the evaluation ofx + y
.
*它不完全等价,因为(a)__rsub __,(b)用C实现的类型(如set),以及(c)查找某些特殊方法与常规方法不同的规则.
内容总结
以上是互联网集市为您收集整理的python中两个赋值运算符有什么区别?全部内容,希望文章能够帮你解决python中两个赋值运算符有什么区别?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。