Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: defining my own operators?

I would like to define my own operator. Does python support such a thing?

like image 485
cwj Avatar asked May 31 '09 16:05

cwj


People also ask

How do you override operators in Python?

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 == .

What is __ add __ in Python?

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.

What is __ MUL __ in Python?

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”).


2 Answers

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 
like image 163
Ayman Hourieh Avatar answered Oct 13 '22 05:10

Ayman Hourieh


No, Python comes with a predefined, yet overridable, set of operators.

like image 43
dfa Avatar answered Oct 13 '22 04:10

dfa