简体   繁体   中英

Defining arithmetic operations on python classes

I'm trying to figure out if it is possible to define arithmetic operations on python classes. What I would like to do something like:

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

a + a

But, of course I get:

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

Is such a thing even possible?

a + a would be interpreted as type(a).__add__(a, a) , which means you have to define the method at the metatype level. For example, a (not necessarily correct) implementation that creates a new class the inherits from the two operands:

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

Then

>>> A + B
<class '__main__.Addable.__add__.<locals>.child'>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM