Python Hidden Features Tutorial

Python Hidden Features are a set of different functions which can be performed by manipulating different objects in Python. Learn more here.

Python Hidden Features: Operator Overloading

Everything in Python is an object. Each object has some special internal methods which it uses to interact with other objects. Generally, these methods follow the action naming convention. Collectively, this is termed as the Python Data Model.

You can overload any of these methods. This is commonly used in operator overloading in Python. Below is an example of operator overloading using Python’s data model. The Vector class creates a simple vector of two variables. We’ll add appropriate support for mathematical operations of two vectors using operator overloading.

class Vector(object):
def init(self, x, y):
self.x = x
self.y = y
def add(self, v):

Addition with another vector.

return Vector(self.x + v.x, self.y + v.y)
def sub(self, v):

Subtraction with another vector.

return Vector(self.x - v.x, self.y - v.y)
def mul(self, s):
Multiplication with a scalar. return Vector(self.x * s, self.y * s)
def div(self, s):
Division with a scalar. float_s = float(s)
return Vector(self.x / float_s, self.y / float_s)
def floordiv(self, s):
Division with a scalar (value floored). return Vector(self.x // s, self.y // s)
def repr(self):
Print friendly representation of Vector class. Else, it would
show up like, <main.Vector instance at 0x01DDDDC8>. return '' % (self.x, self.y, )
a = Vector(3, 5)
b = Vector(2, 7)
print a + b # Output:
print b - a # Output:
print b * 1.3 # Output:
print a // 17 # Output:
print a / 17 # Output:

The above example demonstrates overloading of basic numeric operators. A comprehensive list can be found here.

Learn More

https://codingcompiler.com/unit-testing/

Leave a Comment