1

I've heard that a + b expands to a.__add__(b). However, it doesn't work like that in my code. Take this code:

class TestAdd:
    def __init__(self, a):
        self.a = a
    def __getattr__(self, name):
        if name == '__add__':
            return (lambda y: self.a + y)

When I try TestAdd(5).__add__(1), it returns 6 correctly. When I try TestAdd(5) + 1, it raises this error:

TypeError                                 Traceback (most recent call last)
<ipython-input-3-1c04c7082b89> in <module>
----> 1 TestAdd(5) + 1

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

Why is this? Am I missing something?

Pradhyum R
  • 113
  • 2
  • 12

2 Answers2

0

You can't use __getattr__ to dynamically return a magic method; this is documented in depth in 3.3.10 Special method lookup in the manual.

AKX
  • 152,115
  • 15
  • 115
  • 172
0

Magic methods aren't looked up on instances, but on classes. TestAdd(5) + 1 is more precisely equivalent to tmp = TestAdd(5); TestAdd.__add__(tmp, 1), and you haven't defined TestAdd.__add__.

chepner
  • 497,756
  • 71
  • 530
  • 681