gpt4 book ai didi

python int 没有 __iadd__() 方法?

转载 作者:太空狗 更新时间:2023-10-30 02:06:21 25 4
gpt4 key购买 nike

我知道这是不好的做法:

>>> a = 5
>>> a.__radd__(5)
10
>>> a
5
>>> a.__iadd__(5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute '__iadd__'

出于好奇,如果一个 int 对象没有 __iadd__,那么 += 是如何工作的?

最佳答案

Out of curiosity, if an int object doesn't have __iadd__, then how does += work?

a += 5

成为

a = a + 5

因为不可变对象(immutable对象)没有 __iadd__

这是(实际上)

a = a.__add__( 5 )

而且效果很好。 __add__ 创建了一个新的 int 对象。

一些规则在这里http://docs.python.org/reference/datamodel.html#coercion-rules .

关于python int 没有 __iadd__() 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4088731/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com