Difference between object and instance in python?

Short answer: In python, all objects have a type (returned by type(x)) which is also an object.
if 't' is a type object, then its type is the special type 'type'. So (type(type(x)) is type) is always True. In old classes, a user defined 'class' is a object of the type 'classobj' - and each instance of any class is an object of type 'instance'. I.e. there are two built-in types 'classobj' and 'instance' which implement classes. The linkage from an instance to its class is via its __class__ member.

With new classes: User defined classes are actually new type objects (their type is 'type', not 'classobj') and when you create instances of them, the type() of each instance is the class object. So, objects of different user-defined classes now have distinct types. And classes are on basically the same footing as all builtin types; with old classes there's a separate structure for instance->class and object->type, new classes use object->type for both.

There's much more in the docs, but that's the core of it.


This is the difference between new-style and old-style classes, which is explained in great detail in the documentation. Basically, in Python 2.x you should ensure you always inherit from object so that you get a new-style class. In Python 3, old-style classes have gone away completely.

Tags:

Python

Oop