Module 3 of 6, Python in Depth
Classes in Depth
Plug classes into Python's protocols, choose the right kind of method, and guard attributes.
module checksSign in to track
- Lessons complete-, not done
- Lesson quizzes taken-, not done
- Module Labs passed-, not done
- Module exam passed at 80%-, not done
- lessons
- 3
- quiz questions
- 36
- reading time
- 27 min
- exam length
- 15 Q
- coding exercises
- 6
Lessons
- Special (Dunder) MethodsMake your classes behave like built-in types: __repr__ and __str__ for printing, __eq__ and ordering for comparing, __add__ and friends for arithmetic, and __len__, __getitem__, __contains__ and __iter__ for containers. 9 min 12 questions
- Class Methods and Static MethodsKnow the three kinds of method: instance methods with self, class methods with cls for alternative constructors and class-wide state, and static methods for helpers, plus class attributes and their traps. 9 min 12 questions
- Encapsulation and PropertiesProtect an object's data the Python way: underscore conventions, name mangling, and @property for computed, validated and read-only attributes that callers still use like plain attributes. 9 min 12 questions
Lab: write it yourself
Real Python, real checks: write your answer, press Run checks, and keep going until it passes. (3 exercises)
The Lab needs an account. Sign in or create a free ID to run these exercises.
Lab 1: 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.
Sign in to practise
Sign in to access the interactive Python editor, write and run code checks against automated tests, use hints, and save your practice. Practice does not award XP.
Lab 2: 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.
Sign in to practise
Sign in to access the interactive Python editor, write and run code checks against automated tests, use hints, and save your practice. Practice does not award XP.
Lab 3: 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.
Sign in to practise
Sign in to access the interactive Python editor, write and run code checks against automated tests, use hints, and save your practice. Practice does not award XP.