New Style Classes and Old Style Classes in Python
The parent class of each and every class in Python is the class called object. Everything in Python inherits from this class. That is why it is said that everything in Python is an object. You can do a quick >>> object or >>> help(object) or >>> dir(object) to explore this further.
In Python, there are two alternative ways of defining a base class: class BaseClass(object): and class BaseClass:. In Python 3, it does not make any difference which syntax you use. In Python 2, however, it makes a big difference. Python 3 allows you to drop the word object while declaring a base class, and it will treat the base class the same way. But Python 2 does not, which may lead to a problem. This has to do with Old-style classes and New-style classes.
Python 2 has two types of classes: Old-style classes and New-style classes. The latter were introduced in Python 2.2. The difference between Old-style classes and New-style classes is that
- In Old-style classes, obj.__class__ and type(obj) evaluate to different things. obj.__class__ gives the class name, where as type(obj) gives
. This is due to the fact that all old-style objects/instances, irrespective of their classes, are implemented with a single built-in type called instance. - In New-style classes, obj.__class__ and type(obj) both evaluate to the same thing i.e. the class name.
Apart from this significant difference, there are two additional methods that New-style classes support which Old-style classes don't: mro() and super(). We will get to these later in the chapter.
Python 3 does not support Old-style classes. In fact, there is little chance that you will find a topic in the discussion forums relating to these in Python 3 docs. In Python 2 docs, it lies here.
In Python 2, class BaseClass(object): refer to new-style classes and class BaseClass: refer to old-style classes.
In Python 3, both class BaseClass(object): and class BaseClass: refer to the new-style classes, the latter syntax inherits the object class implicitly.
As you can see, the alternative syntax in Python 3 is the same as the syntax to declare old-style classes in Python 2. Python 2 is still very widely used, such as in Pygame, Web2Py etc. Any attempt to apply the Python 3 class definitions in Python 2 will lead to outdated base objects. And since, this is not a prominently known issue, debugging will be even more difficult.