使 python @property 句柄 +=, -= 等

Eld*_*mir 5 python properties class

Python 文档中,我看到您可以设置透明地处理属性的方法:

class C(object):
    def __init__(self):
        self._x = None

    def getx(self):
        return self._x

    def setx(self, value):
        self._x = value

    def delx(self):
        del self._x

    x = property(getx, setx, delx, "I'm the 'x' property.")
Run Code Online (Sandbox Code Playgroud)

现在假设这C._x是一个列表。在 init 中,它只是设置为[]. 因此,如果我执行以下操作:

c = C()
c.x = [1,2,3]
Run Code Online (Sandbox Code Playgroud)

c.x将被设置为[1,2,3]。我现在想做的是

#...
c.x += 4
Run Code Online (Sandbox Code Playgroud)

c.x现在就是这样[1,2,3,4]。这个例子很简单,但显然,我希望setxgetx方法包括某种处理和检查。否则,使用这种方法将是愚蠢的。

编辑:仅使用该__add__方法C来强制执行行为可能就足够了,但我想知道是否可能将行为放在属性上而不是整个类上

Hol*_*olt 5

您不能重载特定属性的运算符,因为:

c.x += 4
# is equivalent to
c.x.__iadd__(4)
Run Code Online (Sandbox Code Playgroud)

所以实际上你正在调用__iadd__列表的运算符。如果您希望能够做到这一点,您必须创建一个新类,扩展列表并重载运算符__iadd__or __add__

class SuperList(list):
    def __iadd__(self, other):
        if type(other) == list or type(other) == SuperList:
            return super(SuperList, self).__iadd__(other)
        return super(SuperList, self).__iadd__([other])
Run Code Online (Sandbox Code Playgroud)