object
Class and Python Special MethodsNow that we understand inheritance, we can gain a deeper understanding of some of Python’s fundamental special methods.
object
superclassIn 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
. By “ancestor” we mean either a parent class, or a parent of a parent class, etc.
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:
__eq__
, whose default implementation simply uses is
to compare two objects.
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.