Not required, but recommended, and the behavior is different in Python 2 and 3.
According to that documentation, up to version 2.1 the class concept (class
) was different from the concept of type (type
), so that x.__class__
returned the class of x
but type(x)
always returned <type 'instance'>
. From 2.2 these concepts were unified, so that a class "new-style" is simply a user-defined type, and both x.__class__
and type(x)
return the same thing* - the class of x
. The reason cited was:
The biggest motivation to introduce classes new-style 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 types built-in, or the introduction of "Descriptors", that allow computed properties.
For compatibility, the classes "old-style" continued to be supported in Python 2, and the default when using:
class Foo:
is the creation of a class old-style, while when using:
class Foo(object):
creates a class new-style who explicitly inherits from object
. There is little reason to create classes old-style (and some benefits in using the other), so the recommended is always to use the second syntax.
In Python 3, there are no more classes old-style, all classes are new-style by default. So whether you use one or the other syntax, the result will be the same. But for the sake of consistency, so to speak, it is recommended that we still use the second syntax - which makes it more explicit which other class(s) this new class(s) is inheriting.
Some practical differences between classes old-style and new-style:
- 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 that fields are deleted - but one with well defined and fixed fields;
- New ones cannot be launched unless they inherit from
Exception
;
- The method resolution order 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).
Source
* Unless it is clear that the class/object redefines __class__
, but that’s another story...