A.I, Data and Software Engineering

Advanced Python: Object operations and comparisons

A

In many cases, it is convenient to perform mathematical operations on objects rather than numerical values. Python classes have the ability to emulate the behaviour of numeric values to support operations like addition and subtraction. You can override many more to support number-like functionality.

Numeric functions

In the following table, the right column contains expressions that cause these functions to be called;  such as when two objects are added together.

Some object operators

In addition, Python also supports in-place math operations on objects. These functions are called when you use the shorthand notation, such as +=, in order to add to an existing object in-place. 

This is not an exhaustive list. To learn more about these functions, you can check out the data model chapter in the Python documentation.

In the following example, we will create a point class and perform two-point addition and subtraction. The base class look like this:

class Point():
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __repr__(self):
        return "<Point x:{0},y:{1}>".format(self.x, self.y)

Next, we override the __add__, __sub__ and __iadd__ (in-place operators, e.g. +=, -=, /=, etc) to give our objects number-like behaviour.

    # implement addition
    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)
    # implement subtraction
    def __sub__(self, other):
        return Point(self.x - other.x, self.y - other.y)
    # implement in-place addition
    def __iadd__(self, other):
        self.x += other.x
        self.y += other.y
        return self

We can test the overridden behaviors with two new points (10, 20) and (30, 30).

    # Declare some points
    p1 = Point(10, 20)
    p2 = Point(30, 30)
    print(p1, p2)
    #<Point x:10,y:20> <Point x:30,y:30>
    # Add two points
    p3 = p1 + p2
    print(p3)
    #<Point x:40,y:50>
    # subtract two points
    p4 = p2 - p1
    print(p4)
    #<Point x:20,y:10>
    # Perform in-place addition
    p1 += p2
    print(p1)
    #<Point x:40,y:50>

Comparison operators

Similarly, the comparison operators will be triggered when we use comparing symbols, e.g >, >= or ==, etc.

comparison operators table

In the following example, we utilize these methods to compare two employee objects directly by their levels.

class Employee():
    def __init__(self, fname, lname, level, yrsService):
        self.fname = fname
        self.lname = lname
        self.level = level
        self.seniority = yrsService
    # implement comparison functions by emp level
    def __ge__(self, other):
        if self.level == other.level:
            return self.seniority >= other.seniority
        return self.level >= other.level
    def __gt__(self, other):
        if self.level == other.level:
            return self.seniority > other.seniority
        return self.level > other.level

Next, we will define some employees to a list and use sort method to sort these employees based on the overridden comparison operators.

dept = []
dept.append(Employee("Peta", "Mind", 5, 9))
dept.append(Employee("John", "Doe", 4, 12))
dept.append(Employee("Jane", "Smith", 6, 6))
dept.append(Employee("Andrew", "Ng", 5, 13))
dept.append(Employee("Tyler", "Durden", 5, 12))
# Who's more senior using direct comparison?
print(bool(dept[0] > dept[2]))       #False
print(bool(dept[4] < dept[3]))       #True
# sort the items
emps = sorted(dept)
for emp in emps:
    print(emp.lname)
#Doe
#Mind
#Durden
#Ng
#Smith

For more advanced python topic, please go here.

Add comment

A.I, Data and Software Engineering

PetaMinds focuses on developing the coolest topics in data science, A.I, and programming, and make them so digestible for everyone to learn and create amazing applications in a short time.

Categories