【问题标题】:After self addition the object becomes None...?自我添加后,对象变为无......?
【发布时间】:2018-03-03 06:16:00
【问题描述】:

试试这个简单的代码(MCVE):

class Foo(object):
    def __init__(self, val):
        self.v = val

    def __add__(self, other):
        return Foo(self.v + other.v)

    def __iadd__(self, other):
        print('before iadd v = {}'.format(self.v))
        self.v = (self + other).v
        print('after iadd v = {}'.format(self.v))

    def __str__(self):
        return repr(self)

    def __repr__(self):
        return 'Foo.__repr__({})'.format(self.v)

a = Foo(3)
b = Foo(5)
a += b
print('Now a is {}'.format(a))

输出是

before iadd v = 3
after iadd v = 8
Now a is None

我想a += b 应该就地修改a(这就是我在Foo.__iadd__() 中写的内容。这让我困惑了很长时间。我预计最后一行应该是

Now a is Foo.__repr__(8)

【问题讨论】:

    标签: python python-3.x operator-overloading


    【解决方案1】:

    因为您在 __iadd__ 方法中没有返回任何内容。尝试返回 self。

    【讨论】:

    • def __add__(self, other): return Foo(self.v + other.v) 不是返回吗?
    • @iBug:方法错误。
    • @iBug 为 iadd 方法做这个
    • 但是,__iadd__ 不应该就地修改对象吗?
    • @iBug 确实如此。但它会用返回的值修改现有值。由于您什么都不返回,因此结果变为无。
    猜你喜欢
    • 2011-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-18
    • 2015-05-24
    相关资源
    最近更新 更多