Special Methods

Special methods customize how objects behave with Python syntax and built-in functions. They usually have double underscores, such as __eq__, __str__, and __repr__.

Equality

__eq__() controls equality comparison.

class Parent:
    def __eq__(self, other):
        print("Parent's __eq__() called")
        return True
 
class Child(Parent):
    def __eq__(self, other):
        print("Child's __eq__() called")
        return True

When comparing parent and child objects, Python may prefer the child implementation if the child is more specific.

String Representation

__str__() is called by print() and str(). It should be user-friendly.

def __str__(self):
    return "Employee name:{0},\nEmployee salary:{1}".format(self.name, self.salary)

__repr__() is called by repr() and in the console. It should ideally return a string that could recreate the object.

def __repr__(self):
    return "Employee('{name}',{salary})".format(name=self.name, salary=self.salary)

Formatting

Python strings can use .format() with positional or keyword arguments.

"Employee name: {name}".format(name=self.name)