3

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?

GuillaumeDufay
  • 1,118
  • 9
  • 13

1 Answers1

7

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'>
chepner
  • 497,756
  • 71
  • 530
  • 681