且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何为 Python 属性实现 __iadd__

更新时间:2023-12-01 07:53:58

__iadd__ 只会在从 __get__ 返回的值上查找.您需要使用 __iadd__ 使 __get__(或属性 getter)返回一个对象(或代理对象).

__iadd__ will only be looked for on the value returned from __get__. You need to make __get__ (or the property getter) return an object (or a proxy object) with __iadd__.

@property
def x(self):
    proxy = IProxy(self._x)
    proxy.parent = self
    return proxy

class IProxy(int, object):
    def __iadd__(self, val):
        self.parent.iadd_x(val)
        return self.parent.x