Why Do Python Classes Inherit Object?

Better Stack Team
Updated on June 19, 2024

In Python 2.x, it was not necessary to explicitly inherit from the object class when defining a new class. However, in Python 3.x, it is recommended to explicitly inherit from object for several reasons:

  1. In Python 3.x, all classes are by default new-style classes, which provide some additional features and optimizations compared to old-style classes. Explicitly inheriting from object ensures that your class is recognized as a new-style class.
  2. Explicitly inheriting from object makes your code more explicit and descriptive. It clearly indicates that you are defining a class based on the object class, which is the base class for all classes in Python.
  3. Explicitly inheriting from object ensures compatibility between Python 2.x and Python 3.x codebases. While it may not be necessary in Python 2.x, it is a good practice to include it for consistency and future-proofing your code.
  4. Explicitly inheriting from object ensures that the class follows the C3 linearization method for determining the method resolution order (MRO). This can be important in cases where multiple inheritance is used.

Here's an example of explicitly inheriting from object:

 
class MyClass(object):
    pass

In Python 3.x, you can omit the (object) part and simply write:

 
class MyClass:
    pass

Both of these definitions are equivalent, but explicitly inheriting from object is more explicit and recommended for clarity and compatibility reasons.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github