Python Default Inheritance?

If I define a class in Python, for example:

class AClass: __slots__ = ['a', 'b', 'c'] 

What class does he inherit? It does not seem to inherit from object .

+8
python inheritance class
source share
4 answers

If you define a class and do not declare any specific parent, the class becomes a "classic class" that behaves a little differently from the "new style classes" inherited from the object. See here for more details: http://docs.python.org/release/2.5.2/ref/node33.html

Classic classes do not have a common root, so, in fact, your ACL class does not inherit from any class.

Note that this applies to versions of Python prior to 3.0. In Python 3, all classes are new-style classes and are implicitly inherited from an object if no other parent is declared.

+11
source share

Try the following code snippet in Python 2.7 and Python 3.1

 class AClass: __slots__ = ['a', 'b', 'c'] print(type(AClass)) print(issubclass(AClass,object)) print(isinstance(AClass,type)) 

In Python 2.7 you get:

 <type 'classobj'> False False 

And Python 3.1 you get.

 <class type> True True 

And that explains everything. This is an old style class in Python 2, unless you subclass it from object . Only in Python3 will it be processed by default as a new style class.

+8
source share

In Python 2.x or AClass your AClass example is an "old style" class.

The class "new style" has a certain inheritance and must inherit an object or some other class.

What is the difference between old style and new style classes in Python?

EDIT: Wow, I didn't think you could use the old style syntax in Python 3.x. But I just tried, and this syntax still works. But you get a new style class.

+2
source share

Give it a try.

 >>> class AClass: ... pass ... >>> AClass.__bases__, type(AClass) ( (), <type 'classobj'> ) # inherits from nothing >>> class AClass(object): # new style inherits from object ... pass ... >>> AClass.__bases__, type(AClass) ( (<type 'object'>,), <type 'type'> ) 

Read the introduction to the new style classes in the links provided in other answers.

+2
source share

All Articles