7. New and Old style classes

7.1. Rationale

7.1.1. New Style Class

  • Introduced in Python 2.2

  • In Python 3 this is the only way

  • Inherit from object or from another new style class

  • Ability to subclass most built-in types

  • super() added

  • MRO changed

  • descriptors added

  • new style class objects cannot be raised unless derived from Exception

  • __slots__ added

Listing 342. New Style Class
class MyClass(object):
    pass
Listing 343. New Style Class
class MyClass(object):
    pass

class OtherClass(MyClass):
    pass
Listing 344. In Python 3, there are no old-style classes, and this code will produce new style class
class SomeObject:
    pass

7.1.2. Old Style classes

  • Not existing in Python 3

  • Don't inherit from object

class SomeObject:
    pass

Note

In Python 3, there are no old-style classes, and this code will produce new style class

7.1.3. Python 2 vs 3

  • Old style classes are only in Python 2

  • New style classes works in Python 2 (when inherit from object)

  • In Python 3 all classes always inherit from object, hence they are new style classes