worldofprasanna worldofprasanna - 1 year ago 128
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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download