I would like to define my own operator. Does python support such a thing?
In Python, overloading is achieved by overriding the method which is specifically for that operator, in the user-defined class. For example, __add__(self, x) is a method reserved for overloading + operator, and __eq__(self, x) is for overloading == .
The __add__() method in Python specifies what happens when you call + on two objects. When you call obj1 + obj2, you are essentially calling obj1. __add__(obj2). For example, let's call + on two int objects: n1 = 10.
The Python __mul__() method is called to implement the arithmetic multiplication operation * . For example to evaluate the expression x * y , Python attempts to call x. __mul__(y) . We call this a “Dunder Method” for “Double Underscore Method” (also called “magic method”).
While technically you cannot define new operators in Python, this clever hack works around this limitation. It allows you to define infix operators like this:
# simple multiplication x=Infix(lambda x,y: x*y) print 2 |x| 4 # => 8 # class checking isa=Infix(lambda x,y: x.__class__==y.__class__) print [1,2,3] |isa| [] print [1,2,3] <<isa>> [] # => True
No, Python comes with a predefined, yet overridable, set of operators.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With