In Python, I can overload an object's __add__
method (or other double-underscore aka "dunder" methods). This allows me to define custom behavior for my objects when using Python operators.
Is it possible to know, from within the dunder method, if the method was called via +
or via __add__
?
For example, suppose I want to create an object which prints "+"
or "__add__"
depending on if +
was used or if __add__
was called directly.
class MyAdder(object):
def __add__(self, other):
print method_how_created()
return 0
MyAdder() + 7
# prints "+", returns 0
MyAdder().__add__(7)
# prints "__add__", returns 0
Barring the existence of some magic like method_how_created
, is there a canonical mapping of symbols to dunder methods? I know there are lists, such as http://www.python-course.eu/python3_magic_methods.php or solutions based on parsing the docstrings of the operator
module, as mentioned here: Access operator functions by symbol. Is there a way to find a map between function names and symbols that is a little less hacky than parsing the docstrings or manually creating a list?