Module 9
Object-Oriented Programming
// Lessons
6
// Quiz questions
90
// Reading time
180 min
// Exam length
15 Q
// Coding exercises
10
- 1Classes, Objects & BlueprintsInstantiate custom types, bind instance attributes, and define state-modifying behavior. 30 min 15 questions
- 2Constructors & the self BindingInitialize instance state with __init__, distinguish class from instance attributes, and avoid mutable traps. 30 min 15 questions
- 3Class Methods vs Static MethodsBuild alternative constructors with @classmethod and encapsulate pure helper routines with @staticmethod. 30 min 15 questions
- 4Inheritance & Method OverridingExtend base class capabilities, leverage super(), and implement polymorphic interfaces across subclasses. 30 min 15 questions
- 5Encapsulation & @property DecoratorsProtect internal class state with private conventions, validated getters, and setter mutation guards. 30 min 15 questions
- 6Special Dunder MethodsImplement Pythonic operator overloading, developer string representations with __repr__, and length checks. 30 min 15 questions
Coding practice: write it yourself
Real Python, real checks: write your answer, press Run checks, and keep going until it passes. (4 exercises)
Coding practice needs an account. Sign in or create a free ID to run these exercises.
Lab 1: Rectangle class
Create a class Rectangle with __init__(self, width, height) and a method area(self) returning width * height. Test with r = Rectangle(4, 5) and print: Area: 20.
Coding Practice is Locked
Sign in to access the interactive Python editor, write and run code checks against automated tests, use hints, and earn XP.
Lab 2: Custom __str__
Create a class Car with __init__(self, make, model) and __str__(self) returning f"{self.make} {self.model}". Print Car("Tesla", "Model 3"): Tesla Model 3.
Coding Practice is Locked
Sign in to access the interactive Python editor, write and run code checks against automated tests, use hints, and earn XP.
Lab 3: Class method factory
Create a Square class with __init__(self, side). Add @classmethod def from_perimeter(cls, p): return cls(p / 4). Instantiate with Square.from_perimeter(20) and print: Side: 5.0.
Coding Practice is Locked
Sign in to access the interactive Python editor, write and run code checks against automated tests, use hints, and earn XP.
Lab 4: Protected property
Create class Thermometer with @property def kelvin(self) returning self._celsius + 273.15. Set _celsius = 25.0 in __init__. Print: Kelvin: 298.15.
Coding Practice is Locked
Sign in to access the interactive Python editor, write and run code checks against automated tests, use hints, and earn XP.
References & Further Reading
Related entries from PyLabs's own reference library.
- property() (Create a managed attribute for a class.)
- classmethod() (Make a method receive the class instead of an instance.)