"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > The mystery of Python class inheritance: Why do we need to inherit from `object`?

The mystery of Python class inheritance: Why do we need to inherit from `object`?

Posted on 2025-04-30
Browse:688

Why Inherit from `object` in Python: A Class Inheritance Question

Understanding Python Class Inheritance

In Python, classes can inherit from other classes, which grants them access to the parents' attributes and methods. However, one peculiarity that often arises is why classes are declared to inherit from the object class.

Why Inherit from object (Python 2.x vs. Python 3.x)

In Python 2.x, class declarations without an explicit parent class are known as "classic" classes. These classes do not inherit from object and have a number of limitations compared to "new" style classes, which explicitly inherit from object:

  • Lack of descriptor support: Features like classmethod, staticmethod, and property decorators are not available in classic classes.
  • Limited instance creation: The __new__ method, which allows for customization of instance creation, is unavailable in classic classes.
  • Ambiguous method resolution order: The order in which parent classes are searched for methods can be unpredictable in classic classes.
  • Limited access to super calls: Super calls, which invoke methods from parent classes, are not supported in classic classes.

In Python 3.x, the distinction between classic and new style classes is eliminated. All classes are considered new style classes and implicitly inherit from object without the need for explicit declaration.

Should You Inherit from object in Python 3?

While inheriting from object is optional in Python 3, it does not provide any benefits or drawbacks. However, for compatibility reasons, it is recommended to inherit from object when writing code that may need to run in both Python 2.x and Python 3.x.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3