CS 238 Week 4 Lecture
Watch on YouTube →
Overview
James Andro-Vasko introduces Python inheritance through a Square base class and a Cube subclass, showing how a subclass can reuse inherited methods, override get_area(), and add get_volume(). He demonstrates super() for calling the base class’s get_area() and __init__(), while using a cube’s side length and depth to compute its surface area and volume.
Key takeaways
- In Python, class Cube(Square) inherits the base class’s available methods and constructor, so a subclass can initially reuse behavior without defining anything itself.
- A subclass can replace an inherited method: Cube.get_area() computes six face areas by calling super().get_area() and multiplying the result by 6.
- Use super().method() to call a base-class implementation from an override; self.get_area() inside Cube.get_area() would resolve to the override itself.
- Python selects an overridden method based on the object’s class: a Cube instance uses Cube.get_area(), while a Square instance uses Square.get_area().
- A subclass constructor can initialize inherited state with super().__init__(side) and then add subclass-specific state such as Cube.depth.
- Python’s double-underscore attribute syntax performs name mangling, not strict privacy; the lecture’s Square example uses it to discourage direct access to __side.
Chapters
0:00
Square and Cube: Reusing Base-Class Behavior
- Inheritance lets a Python class reuse code from a base class rather than copy and paste it; Andro-Vasko introduces the idea with Square and Cube.
- Square stores a side value and provides get_perimeter() and get_area() methods.
- Defining class Cube(Square) gives Cube access to Square’s constructor and methods even when Cube initially contains only pass.
6:00
Override Cube.get_area() with super()
- A cube’s surface area is six times the area of one square face, so Cube overrides get_area() to multiply the inherited area by 6.
- The override calls super().get_area() to run Square’s area calculation; calling self.get_area() would call the Cube override again.
- Method dispatch depends on the object: c.get_area() uses Cube’s override for a Cube instance, while s.get_area() uses Square’s method for a Square instance.
11:00
Add Cube Volume and Initialize the Base Class
- Cube adds get_volume(), calculating volume as super().get_area() multiplied by the cube’s stored depth.
- Cube defines its own __init__(side), calls super().__init__(side) to initialize the inherited side value, and stores side as depth for the volume calculation.
- The lecture uses a double-underscore __side attribute to illustrate restricted access; in Python, double underscores trigger name mangling rather than making an attribute truly private.
Summary, takeaways, and chapters were generated by AI from the video's transcript and may contain errors. The video belongs to its creator, James Andro-Vasko.