gpt4 book ai didi

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

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

来自 Python documentation ,我看到您可以透明地设置处理属性的方法:

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

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

c = C()
c.x = [1,2,3]

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

#...
c.x += 4

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

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

最佳答案

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

c.x += 4
# is equivalent to
c.x.__iadd__(4)

所以实际上您正在调用列表的 __iadd__ 运算符。如果您希望能够做到这一点,您必须创建一个新类、扩展列表和重载运算符 __iadd____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])

关于python - 使 python @property 句柄 +=, -= 等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23288559/

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