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:

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

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

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.

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

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.

Pin It on Pinterest

Newsletters

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

Petaminds will use the information you provide on this form to be in touch with you and to provide updates.