worldofprasanna worldofprasanna - 3 months ago 20
Python Question

Add our own mapping of magic methods

Recently I was reading about magic methods in Python, which make the code a lot easier to read. Can we define our own mappings? If so, is there any pointer for this and how complicated it would be?

For example,

+
is always mapped to
__add__
. Could I define a mapping for
?
, which would call
__is_valid__
in my class?

c = Car()
print(c?) # invokes __is_valid__ of Car to get the result

Answer

You seem to be asking if you can create your own syntax in Python, adding new symbols that are implemented via magic methods. The answer is no. The only operators available are the ones that already exist (+, *, etc.), and each has its corresponding magic methods. You can't add new ones.

Comments