class ClassName versus class ClassName(object)

<>

This question already has an answer here:

Answers


In Python 2.x, when you inherit from "object" you class is a "new style" class - that was implemented back in Python 2.2 (around 2001) - The non inheriting from "object" case creates an "old style" class, that was actually maintained only for backwards compatibility.

The great benefit of "new style" classes is the unification of types across Python - prior to that, one could not subclass built-in types such as int, list, dict, properly. There was also specified a "descriptor protocol" which describes a protocol for retrieving and setting attributes in an object, giving the language a lot of flexibility. (It is more visible when one does use a Python "property" in a class).

What does make the difference is not actually "inheriting from object", but, since classes in Python are also objects, that does change the class'class itself (a class'class is known as its "metaclass"). Thus if you set the metaclass to be "type", you don't need to inherit from object to have a new style class.

It is strongly recommended that in Python 2.x, all your classes are new style - using old style classes may work for some single straightforward cases, but they can generate a lot of subtle, difficult to find, errors, when you try to use properties, pickle, descriptors, and other advanced features. Above all, when you try to check the "type" of an object, it will be the same (type "instance") for all objects from old style classes, even if they are from different user defined classes.

In Python versions 3.x all classes are new style - no need to set the metaclass.

Python's documentation "datamodel" is the "book of law" where the behavior of both class typs is defined in detail (enough to allow one to reimplement the language):

http://docs.python.org/reference/datamodel.html

This blog post from Guido talks about the motivations behind new style classes in a lighter language:

http://python-history.blogspot.com.br/2010/06/new-style-classes.html

http://docs.python.org/release/2.5.2/ref/node33.html


ClassName(object) uses the new style class: http://docs.python.org/release/2.5.2/ref/node33.html

The second example demonstrates an old style class.

In python 3, new style classes are used by default and you will no longer need to subclass object.


Need Your Help

How to use a lambda expression as a template parameter?

c++ templates c++11 lambda

How to use lambda expression as a template parameter? E.g. as a comparison class initializing a std::set.

Digest authentication with Jersey Client

java jersey http-authentication

I have written a REST web service with Jersey Server (that totally rocks !).