Designing with Classes
So far, we’ve concentrated on the OOP tool in Python—the class. But OOP is also about design issues—how to use classes to model useful objects. In this section, we’re going to touch on a few OOP core ideas and look at some examples that are more realistic than the ones we’ve seen so far. Most of the design terms we throw out here require more explanation than we can provide; if this section sparks your curiosity, we suggest exploring a text on OOP design or design patterns as a next step.
Python and OOP
Python’s implementation of OOP can be summarized by three ideas:
- Inheritance
Is based on attribute lookup in Python (in
X.nameexpressions).- Polymorphism
In
X.method, the meaning ofmethoddepends on the type (class) ofX.- Encapsulation
Methods and operators implement behavior; data hiding is a convention by default.
By now, you should have a good feel for what inheritance is all about in Python. Python’s flavor of polymorphism flows from its lack of type declarations. Because attributes are always resolved at runtime, objects that implement the same interfaces are interchangeable; clients don’t need to know what sort of object is implementing a method they call.[47] Encapsulation means packaging in Python, not privacy; privacy is an option, as we’ll see later in this chapter.
OOP and Inheritance: “is-a”
We’ve talked about the mechanics of inheritance in depth already, but we’d like to show you an example of how it can be used to model real-world relationships. From ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access