worldofprasanna worldofprasanna - 2 months ago 4x
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
. Could I define a mapping for
, which would call
in my class?

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


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.