3.9 The object Class and Python Special Methods

3.9 The object Class and Python Special Methods#

Now that we understand inheritance, we can gain a deeper understanding of some of Python’s fundamental special methods.

The object superclass#

In our very first lecture, we described every piece of data as an object, and have continued to use this term throughout this course. It turns out that “object” is not merely a theoretical concept, but made explicit in the Python language. In Python, we have a class called object, which is an ancestor of every other class, both built-in classes like int or our user-defined classes like Employee.[1]

Inheriting special methods#

This object class gives default implementations for many special methods we have seen before, including:

  • __init__, which allows us to create instances of a class even when the class body is empty—it’s not magic, our classes simply inherit object.__init__! So every time we define __init__ within our own class, we are actually overriding object.__init__.

  • __str__, which is called when you call either str or print on an object. The default implementation? Identifying the class name and a location in your computer’s memory:

    >>> class Donut:
    ...    pass
    ...
    >>> d1 = Donut()
    >>> print(d1)
    <Donut object at 0x103359828>
    
  • __eq__, which is called when you use == to compare objects. The default object.__eq__implementation simply uses is to compare the two objects.

    >>> donut1 = Donut()
    >>> donut2 = Donut()
    >>> donut1 == donut2  # compares `donut1 is donut2`, which is False
    False
    >>> donut1 == donut1  # compares `donut1 is donut1`, which is True
    True
    

Keep in mind that even though these methods are called “special”, overriding them in your classes works in the exact same way as other methods: simply define a method with the specific name of that special method.