Previous: Class Inheritance

Python allows you to define special methods for operators and functions to perform common operations.

You can use: the + operator to concatenate two strings, the * operator to concatenate the same string multiple times, the relational operators (==, !=, <, <=, >, and >=) to compare two strings, and the index operator[] to access a character.

Some common Special Methods for Operator Overloading:

Without __str__:

# Operator Overloading, through Special Methods

class Student:
    def __init__(self, name, year):
        self.name = name
        self.year = year

def main():
    s1 = Student('James A', 2003)
    s2 = Student('Chris B', 2004)
    print(s1)
    print(s2)

main()

Output:

<__main__.Student object at 0x10d28cec0>
<__main__.Student object at 0x10d28cf80>

With __str__:

# Operator Overloading, through Special Methods

class Student:
    def __init__(self, name, year):
        self.name = name
        self.year = year

    def __str__(self):
        return f"{str(self.year)} | {self.name}"

def main():
    s1 = Student('James A', 2003)
    s2 = Student('Chris B', 2004)
    print(s1)
    print(s2)

main()

Output:

2003 | James A
2004 | Chris B