我有一个类,它是成员的容器。所有成员都属于同一类型。
class A(int):
def __init__(self, n):
super().__init__()
self.n = n
def do(self):
print('adding 10')
return self.n + 10
class B:
def __init__(self, a1, a2):
self.a = [a1, a2]
def __getattr__(self, item):
return getattr(self.a[0], item)
a1 = A(10)
a2 = A(5)
b = B(a1, a2)
the __getattr__
覆盖do
method:
In[7]: b.do()
adding 10
Out[7]: 20
甚至覆盖__add__
当显式调用时
In[8]: b.__add__(1)
Out[8]: 11
but __add__
调用时失败+
In[9]: b+1
TypeError: unsupported operand type(s) for +: 'B' and 'int'
如何重写魔术方法以按预期工作?
运营商不处理的原因__getattr__
被覆盖在为什么 __getattr__ 能够处理 python 2.x 中的内置运算符重载?
在新式类中,特殊方法总是在类中查找(隐式查找)而不是实例中。
我的解决方法(并不完美,但允许使其工作)是在中显式定义所需的 dunder 方法B
,并显式调用__getattr__
在他们:
class B:
def __init__(self, a1, a2):
self.a = [a1, a2]
def __add__(self,other):
return self.__getattr__("__add__")(other)
def __getattr__(self, item):
return getattr(self.a[0], item)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)