This is not required, but it is recommended, and the behavior is different in Python 2 and 3.
According to this documentation , until version 2.1 class concept ( class
) was different from the type concept ( type
), so that x.__class__
returned the class of x
but type(x)
always returned <type 'instance'>
. From 2.2 these concepts have been unified, so a new-style class is simply a user-defined type, and both x.__class__
and type(x)
return the same thing * - a class of x
. The reason cited was:
The greatest motivation to introduce new-style classes is to promote the unification of an object model with a complete meta-model. It also has some practical benefits, such as the ability to create subclasses of most built-in types, or the introduction of descriptors , which allow computed properties. >
For compatibility, the "old-style" classes continued to be supported in Python 2, and the default when using:
class Foo:
is the creation of an old-style class, while using:
class Foo(object):
If you create a new-style class that inherits explicitly from object
. There is little reason to create old-style classes (and some benefits in using the other), so the second syntax is always recommended.
In Python 3, there are no old-style classes, all classes are new-style by default. So either way if you use either syntax, the result will be the same. But for the sake of consistency, so to speak, it is recommended that you still use the second syntax - which makes it more explicit of which other class (s) this new class is inheriting.
Some practical differences between the old-style and new-style classes:
- The new ones allow the use of
super
, to access members of the superclasses directly;
- The new ones allow the use of
__slots__
, when you do not want an "open" class - that accepts new fields or which fields are deleted - but one with well defined and fixed fields;
- New ones can not be released, unless they inherit from
Exception
;
- The order of method resolution is different, when there is multiple inheritance involved (i.e. which superclass is visited first, when the method does not exist in the class itself).
Font
* Unless of course the class / object redefines __class__
, but that's another story ...