Problem
What is the difference between old style and new style classes in Python? When should I use one or the other?
Declaration-wise:
New-style classes inherit from object, or from another new-style class.
class NewStyleClass(object):
pass
class AnotherNewStyleClass(NewStyleClass):
pass
Old-style classes don’t.
class OldStyleClass():
pass
Python 3 Note:
Python 3 doesn’t support old style classes, so either form noted above results in a new-style class.
Also, MRO (Method Resolution Order) changed:
- Classic classes do a depth first search from left to right. Stop on first match. They do not have the mro attribute.
- New-style classes MRO is more complicated to synthesize in a single English sentence. One of its properties is that a Base class is only searched for once all its Derived classes have been. They have the mro attribute which shows the search order.
Some other notes:
- New style class objects cannot be raised unless derived from
Exception
. - Old style classes are still marginally faster for attribute lookup.