Chapter 6. Classes and Objects: Beyond the Basics

This chapter assumes you are familiar with the basics of object-oriented programming (OOP) in Python: creating classes, defining methods, and simple inheritance. You will build on that knowledge in this chapter.

As with any object-oriented language, it’s useful to learn about design patterns—reusable solutions to common problems involving classes and objects. A lot has been written about design patterns. And while much of it applies to Python, it tends to apply differently.

That is because many design-pattern books and articles are written for languages like Java, C++, and C#. But as a language, Python is different. Its dynamic typing, first-class functions, and other additions all mean the “standard” design patterns just work differently.

So let’s learn what Pythonic OOP is really about.

Properties

Python objects have attributes. “Attribute” is a general term meaning “whatever is to the right of the dot” in an expression like x.y or z.f(). Member variables and methods are two kinds of attributes. But Python has another kind of attribute called properties.

A property is a hybrid: a cross between a method and a member variable. The idea is to create an attribute that acts like a member variable from the outside, but reading or writing to this attribute triggers method calls internally.

You’ll set this up with a special decorator called @property. A simple example:

class Person:
    def __init__(self, firstname, lastname):
        self.

Get Powerful 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.