Override Magic Methods

Making Objects Printable

class Employee: 
    def __init__(self, name, age, eid): 
        self.name = name 
        self.age = age
        self.eid = eid 

employeeObject = Employee('employeeName', 20, 1101)

print(employeeObject)

Outputs

<__main__.Employee object at 0x000001DBB695FB50>

This occurs because we did not code a behaviour for our objects when they are used in String Scenarios. We must override two functions: str() and repr().

To make an object printable.

We must override two built-in base functions in Python:

  1. __str__()

  2. __repr__()

The __str__() method returns a human-readable, or informal, string representation of an object. Often called when the object is within a print() or str()

The __repr__() method returns a more information-rich, or official, string representation of an object. This is often called when your custom object needs to be displayed within another or any other sitution where __str__() is not used.

Fixing the Employee classes

Outputs:

Other Base Functions to Override.

Addition, Subtraction, Multiplication, Division

The built-in arithmetic operators can be overridden to allow your custom class objects to interact with them. The subtraction, multiplication, and division operators will be overridden similar to the addition method above.

Make our objects comparable

If you need more overrides for built-in features of Python, please let me know!

Last updated