Skip to main content
 首页 » 编程设计

python之如何将 "x += 5"(x 为自定义类)添加到 x 的属性中

2025年05月04日12飞鱼

我有这样一个类:

class C(object): 
    a = 5 
    def __iadd__(self, other): 
        self.a += other 

我希望能够做这样的事情:

b = C() 
b += 7 

同样有 b,但 b.a 加了 7。但是,如果我真的运行它,它会将 b 变成一个 NoneType 对象。我假设这是因为 C.__iadd__ 没有返回任何东西。

我是否必须让 C.__iadd__ 返回一个修改过 self.a 的 self 副本?有没有一种方法可以在不复制整个对象并返回的情况下实现这种添加?

请您参考如下方法:

您忘记从 __iadd__ 方法返回 self:

def __iadd__(self, other): 
    self.a += other 
    return self 

来自object.__iadd__() documentation :

These 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).

如果没有明确的 return 语句,函数将返回 None 作为默认值,因此 b += 7 生成 None,这是作业。