Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between class foo and class foo(object) in Python

Tags:

python

Prior to python 2.2 there were essentially two different types of class: Those defined by C extensions and C coded builtins (types) and those defined by python class statements (classes). This led to problems when you wanted to mix python-types and builtin types. The most common reason for this is subclassing. If you wanted to subclass the list type in python code, you were out of luck, and so various workarounds were used instead, such as subclassing the pure python implementation of lists (in the UserList module) instead.

This was a fairly ugly, so in 2.2 there was a move to unify python and builtin types, including the ability to inherit from them. The result is "new style classes". These do have some incompatible differences to old-style classes however, so for backward compatability the bare class syntax creates an old-style class, while the new behaviour is obtained by inheriting from object. The most visible behaviour differences are:

  • The method resolution order (MRO). There is a difference in behaviour in diamond-shaped inheritance hierarchies (where A inherits from both B and C, which both inherit from a common base class D. Previously, methods were looked up left-to right, depth first (ie A B D C D) However if C overloads a member of D, it won't be used by A (as it finds D's implementation first) This is bad for various styles of programming (eg. using mixin classes). New style classes will treat this situation as A B C D, (look at the __mro__ attribute of a class to see the order it will search)

  • The __new__ constructor is added, which allows the class to act as a factory method, rather than return a new instance of the class. Useful for returning particular subclasses, or reusing immutable objects rather than creating new ones without having to change the creation interface.

  • Descriptors. These are the feature behind such things as properties, classmethods, staticmethods etc. Essentially, they provide a way to control what happens when you access or set a particular attribute on a (new style) class.


class foo(object): is the 'new' way of declaring classes.

This change was made in python 2.2, see this PEP for an explanation of the differences.


Subclassing object yields a new-style class. Two well known advantages of new-style classes are:

  • Metaclasses (like class factories, but works transparently)
  • Properties (getters & setters...)

Referring to this The object in class Foo(object) is meant to make your python 3 code compatible with python 2 and 3.