用__getattr__覆盖魔术方法

时间:2020-01-10 14:49:18

标签: python python-3.x magic-methods

我有一个类,它是成员的容器。所有成员都是同一类型。

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)

__getattr__覆盖do方法:

In[7]: b.do()
adding 10
Out[7]: 20

甚至在显式调用时会覆盖__add__

In[8]: b.__add__(1)
Out[8]: 11

但是当__add__称为+

时失败
In[9]: b+1
TypeError: unsupported operand type(s) for +: 'B' and 'int'

如何覆盖魔术方法以按预期工作?

1 个答案:

答案 0 :(得分:2)

Why is __getattr__ capable of handling built-in operator overloads in python 2.x?涵盖了__getattr__不处理运算符的原因

在新型类中,特殊方法总是在类(隐式查找)而不是实例中查找。

我的解决方法(虽然不完美,但可以使其工作)是在B中显式定义所需的dunder方法,并在它们上显式调用__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)
相关问题