在python类上定义算术运算

Gui*_*fay 2 python python-3.x

我试图找出是否有可能在python类上定义算术运算。我想做些什么:

class a():
    @classmethod
    def __add__(cls, other):
        pass

a + a
Run Code Online (Sandbox Code Playgroud)

但是,我当然知道:

TypeError: unsupported operand type(s) for +: 'type' and 'type'

这样的事情有可能吗?

che*_*ner 5

a + a将被解释为type(a).__add__(a, a),这意味着您必须在元类型级别定义方法。例如,一个(不一定正确的)实现创建了一个新类,该类从两个操作数继承:

class Addable(type):
    def __add__(cls, other):
        class child(cls, other, metaclass=Addable):
            pass
        return child

class A(metaclass=Addable):
    pass

class B(metaclass=Addable):
    pass
Run Code Online (Sandbox Code Playgroud)

然后

>>> A + B
<class '__main__.Addable.__add__.<locals>.child'>
Run Code Online (Sandbox Code Playgroud)