4.11. New and Old Style Classes

4.11.1. Rationale

4.11.1.1. Old Style classes

  • Not existing in Python 3

  • Don't inherit from object

Listing 4.48. Python 2 Old Style Class
class MyClass:
    pass

Note

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

4.11.1.2. 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

4.11.2. Python 2

Listing 4.49. New Style Class
class MyClass(object):
    pass
Listing 4.50. New Style Class
class MyClass(object):
    pass

class Child(MyClass):
    pass

4.11.3. Python 3

Listing 4.51. In Python 3, there are no old-style classes, and this code will produce new style class
class MyClass:
    pass

4.11.3.1. 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