Classes and Instances

If you’re already familiar with object-oriented programming in other languages such as C++ or Java, then you probably have a good intuitive grasp of classes and instances: a class is a user-defined type, which you can instantiate to obtain instances, meaning objects of that type. Python supports these concepts through its class and instance objects.

Python Classes

A class is a Python object with several characteristics:

  • You can call a class object as if it were a function. The call returns another object, known as an instance of the class; the class is also known as the type of the instance.

  • A class has arbitrarily named attributes that you can bind and reference.

  • The values of class attributes can be descriptors (including functions), covered in Descriptors, or normal data objects.

  • Class attributes bound to functions are also known as methods of the class.

  • A method can have a special Python-defined name with two leading and two trailing underscores. Python implicitly invokes such special methods, if a class supplies them, when various kinds of operations take place on instances of that class.

  • A class can inherit from other classes, meaning it delegates to other class objects the lookup of attributes that are not found in the class itself.

An instance of a class is a Python object with arbitrarily named attributes that you can bind and reference. An instance object implicitly delegates to its class the lookup of attributes not found in the instance itself. The class, ...

Get Python in a Nutshell, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.