#๐ dunder method questions
33 messages ยท Page 1 of 1 (latest)
@azure ibex
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
Think about Number(5) + Number(5) + Number(5) actually become
Number(5).__add__(Number(5)).__add__(Number(5))
So when you compute Number(5).__add__(Number(5)) and get the equivalent of Number(10), it essentially becomes Number(10).__add__(Number(5)
Basically syntax sugar kind of thing
- Eventually it go to level of C++ code which handled it
There's no "triggering another one" in the int class
Which in turn uses a binary algorithm to add ints
Well, C
CPython, not CppPython hah
the official Python interpreter is written in C
all the builtin types are written in C
it's a python object still, just at the C level
why would the __add__ in int cause Number.__add__ to be triggered?
damn, I didn't see the history
anyways, instead of TypeError you should just return NotImplemented
this lets the other operand implement its own __add__
(Well, __radd__?)
That was to increase priority of the reverse first I think
Even if it works without reversing
!e
class A:
def __add__(self, other):
print("add first")
class B:
def __radd__(self, other):
print("radd first")
A() + B()
:white_check_mark: Your 3.13 eval job has completed with return code 0.
add first
nope
Hmm
it goes like this
- try to call
__dunder__on the LHS - if that fails, try to call
__rdunder__on the RHS
!e therefore, this errors
class A: ...
class B:
def __add__(self, other):
print("add")
A() + B()
:x: Your 3.13 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File [35m"/home/main.py"[0m, line [35m7[0m, in [35m<module>[0m
003 | [31mA() [0m[1;31m+[0m[31m B()[0m
004 | [31m~~~~[0m[1;31m^[0m[31m~~~~[0m
005 | [1;35mTypeError[0m: [35munsupported operand type(s) for +: 'A' and 'B'[0m
Hmm ok
part of the reason is that you can't assume the operator is commutative for the given operands
for example, string concatenation is not commutative
This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.