Class Basics

If you’ve never been exposed to OOP in the past, classes can be somewhat complicated if taken in a single dose. To make classes easier to absorb, let’s start off by taking a quick first look at classes in action here, to illustrate the three distinctions described previously. We’ll expand on the details in a moment; but in their basic form, Python classes are easy to understand.

Classes Generate Multiple Instance Objects

As we mentioned at the end of Chapter 5, classes are mostly just a namespace, much like modules. But unlike modules, classes also have support for multiple copies, namespace inheritance, and operator overloading. Let’s look at the first of these extensions here.

To understand how the multiple copies idea works, you have to first understand that there are two kinds of objects in Python’s OOP model—class objects and instance objects. Class objects provide default behavior and serve as generators for instance objects. Instance objects are the real objects your programs process; each is a namespace in its own right, but inherits (i.e., has access to) names in the class it was created from. Class objects come from statements and instances from calls; each time you call a class, you get a new instance. Now, pay attention, because we’re about to summarize the bare essentials of Python OOP.

Class objects provide default behavior

The class statement creates a class object and assigns it a name

Like def, the Python class statement is an executable statement; when ...

Get Learning Python 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.