1.

Does Python support operator overloading? How?

Answer»

Certain non-alphanumeric characters are defined to perform a SPECIFIED operation. Such characters are called operators. For example the characters +, -, * and / are defined to perform arithmetic operations on two numeric operands. Similarly <, > == and != perform comparison of two numeric operands by default.

Some of built-in classes of Python allow certain operators to be used with non-numeric objects too. For instance the + operator acts as concatenation operator with two strings. We SAY that + operator is OVERLOADED. In general overloading refers to attaching additional operation to the operator.

>>> #default addition operation of + >>> 2+5 7 >>> #+operator overloaded as concatenation operator >>> 'Hello'+'Python' 'HelloPython' >>> [1,2,3]+[4,5,6] [1, 2, 3, 4, 5, 6] >>> #default multiplication operation of * >>> 2*5 10 >>> #overloaded * operator as repetition operation with sequences >>> [1,2,3]*3 [1, 2, 3, 1, 2, 3, 1, 2, 3] >>> 'Hello'*3 'HelloHelloHello'

For user defined classes, operator overloading is achieved by overriding relevant magic methods (methods with two underscores before and after name) from the object class. For example, if a class contains overridden definition of __add__() method, it is implemented when + operator is used with objects of that class. Following table SHOWS magic methods and the arithmetic operator they implement:

OperatorMethod
+object.__add__(self, other)
-object.__sub__(self, other)
*object.__mul__(self, other)
//object.__floordiv__(self, other)
/object.__div__(self, other)
%object.__mod__(self, other)
**object.__pow__(self, other[, modulo])

Following script contains a class that overrides __add__() method. It causes + operator overloading.

>>> class MyClass: def __init__(self, x,y): self.x=x self.y=y def __add__(self, OBJ): x=self.x+obj.x y=self.y+obj.y print ('x:{} y:{}'.format(x,y))

We now have two objects of above class and use + operator with them. The __add__() method will implement overloaded behaviour of + operator as below:

>>> m1=MyClass(5,7) >>> m2=MyClass(3,8) >>> m1+m2 x:8 y:15

Similarly comparison operators can also be overloaded by overriding following magic methods:

<
object.__lt__(self, other)
<=
object.__le__(self, other)
==
object.__eq__(self, other)
!=
object.__ne__(self, other)
>=
object.__ge__(self, other)


Discussion

No Comment Found