Why does inheritance from an object matter in Python?

When a class is inherited from nothing, I have an instance type object.

>>> class A(): pass; >>> a = A() >>> type(a) <type 'instance'> >>> type(a) is A False >>> type(A) <type 'classobj'> 

However, when I have the same class inheriting from the object, the created object is of type A.

 >>> class A(object): pass; >>> a = A() >>> type(a) <class '__main__.A'> >>> type(a) is A True >>> type(A) <type 'type'> 

What is the logic behind this? Does this mean that every class should inherit an object ?

+4
source share
3 answers

In Python 3, these two values โ€‹โ€‹are the same. However, in Python 2:

 class A: pass # old-style class class B(object): pass # new-style class 

From the new and classic classes in the documentation:

Prior to Python 2.1, only old-style classes were used. The concept of a class (old-style) is not related to the concept of a type: if x is an instance of an old-style class, then x.__class__ denotes a class x , but type(x) always <type 'instance'> . This reflects the fact that all instances of the old style, regardless of their class, are implemented using a single built-in type called an instance.

Python 2.2 introduced new-style classes to unify classes and types. A new style class is no more and no less than a custom type. If x is an instance of a new style class, then type(x) same as x.__class__ .

The main motivation for introducing new style classes is to provide a single object model with a complete metamodel. It also has a number of immediate advantages, such as the ability to subclass most of the built-in types or the introduction of "descriptors" that allow you to calculate properties.

For these reasons, it is recommended that you use new-style classes whenever possible. The only reason old style classes exist even in Python 2.2+ is backward compatibility; Python 3 removed old-style classes.

+7
source

The original implementation of custom classes in Python is sucked in. 2.2 fixed it, but they had to keep the old system for backward compatibility. Thus, Python has 2 types of classes, "classic" and "new." Everything that inherits from object (directly or indirectly) is a new style; everything that is not classic. Each class that you write must somehow inherit the object, either directly if it has no other parents, or indirectly, because it inherits from another class of the new style (or built-in type).

See http://python-history.blogspot.com/2010/06/new-style-classes.html

+1
source

this explains the instance thing:

 >>> class A(): pass; >>> A <class __main__.A at 0x7f879998b050> >>> A() <__main__.A instance at 0x7f87999a83b0> 

but you should not use type() to compare objects in python anyway, you should use isinstance()

0
source

Source: https://habr.com/ru/post/1498090/


All Articles