3 ms·
>As a bonus, this also adds support for adding two MyNumber classes together: Merely having `__add__` (without `__radd__`) is enough to add two MyNumber classe
by thrdbndndn 5y ago
>As a bonus, this also adds support for adding two MyNumber classes together:
Merely having `__add__` (without `__radd__`) is enough to add two MyNumber classes together in your case.
>It mostly exists to support type annotations,
The link for "type annotations" is broken.
- tusharsadhwani 5y agoType annotations link is fixed, thank you! Just `__add__` doesn't work for me. I get: TypeError: unsupported operand type(s) for +: 'int' and 'Number' Here's the code: class Number: def __add__(self, x): return 42 + x num = Number() print(num + num) Edit: Okay. replacing `42 + x` with `x + 42` actually makes it work. But I'll be honest I have no idea what happened there.
- thrdbndndn 5y agoIt took me quite a long time to understand what happened there too! (Pseudo code, let's call them num1 and num2 for better readability) num1 + num2 = num1.__add__(num2) = num2 + 42 (that's why the order is important) = num2.__add__(42) = 42 + 42 = 84
- thrdbndndn 5y ago>Type annotations link is fixed, thank you! I'm not sure about that - it's still `<a href="mypy-guide">type annotations</a>` which jumps to https://sadh.life/post/builtins/mypy-guide https://sadh.life/post/builtins/mypy-guide and then jumps to your homepage.