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


In Python 2.x there's two styles of classes depending on the presence or absence of a built-in type as a base-class −

"classic" style or old style classes have no built-in type as a base class:
>>> class OldSpam:      # no base class
...     pass
>>> OldSpam.__bases__
()

"New" style classes: they have a built-in type as a base class meaning that, directly or indirectly, they have object as a base class −

>>> class NewSpam(object):           # directly inherit from object
...    pass
>>> NewSpam.__bases__
(<type 'object'>,)
>>> class IntSpam(int):              # indirectly inherit from object...
...    pass
>>> IntSpam.__bases__
(<type 'int'>,)
>>> IntSpam.__bases__[0].__bases__   # ... because int inherits from object
(<type 'object'>,)

When writing a class one would always want to go for new-style classes. The advantages of doing so are numerous, to list some of them −

Support for descriptors. Specifically, the following constructs are made possible with descriptors −

classmethod − A method that receives the class as an implicit argument instead of the instance.

staticmethod − A method that does not receive the implicit argument self as a first argument.

properties with property: Create functions for managing the getting, setting and deleting of an attribute.

Python 3.x supports only new style classes implicitly. There is no need to mention the word object in parentheses in class declaration.  

Updated on: 15-Jun-2020

431 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements