Unit 9: OOP in Python
1 Overview
We learned about Python classes last semester in SD211 (for one whole week), where you saw how to write and use classes that have a few class functions and object variables.
In this unit, we will recollect what we learned earlier, and go further to understand two new concepts: inheritance (when a class extends or derives from another class) and operator overloading (how to control the way built-in python operators and functions work with classes we write).
As we dive back into classes and learn these new tricks, we want to emphasize the bigger picture as well: what are classes really about, and when would I want to use one? Object-oriented programming is a way of thinking about programs that is based around classes. The powerful thing we can do with a class is to create a new type which encompasses both data (object variables) and functions which operate on that data. For those reasons, objects (i.e., classes) are a very useful tool in organizing larger programs, and especially creating and sharing libraries in Python.
Plus, your understanding of classes will be crucial to your success in the SD311 Data Structures and Scalability course you will take next fall. So let’s get into it!
2 Resources
Python for Everybody, Chapter 14: Object-Oriented Programming
We looked at the beginning of this chapter last semester, but now we should be able to understand the whole thing.
-
This is from the official Python documentation, but meant to be a readable “tutorial” rather than a complete documentation. It’s pretty good!
Focus on the few paragraphs at the top introducing classes, then all of section 9.3 on how classes work, and finally section 9.5 on inheritance.
Skip the part on namesspaces (section 9.1)
Python in a Nutshell, Chapter 4: Object-Oriented Python
This book gets into a lot more detail on how classes work. Too much detail, actually. But it’s still a good reference and fills in some gaps where the “Python for Everybody” book doesn’t go far enough.
Skip to the sections on special methods which covers all the different ways operator overloading and class customization are possible, and decorators which covers how to use
@classmethod
and@staticmethod
.