CS 238 Week 5 Lecture
Watch on YouTube →
Overview
James Andro-Vasko demonstrates Python polymorphism by storing `Cube` and `Square` objects together in a list or dictionary and calling methods on each object without checking its type. The examples show runtime method dispatch, inherited methods, and how missing methods cause `AttributeError`; defining a placeholder such as `pass` or returning `0` avoids the error, though method behavior should still make sense for each shape.
Key takeaways
- Python can hold different object types in one list or dictionary and resolve a method call at runtime based on the object's class.
- In the example, `Cube(7)`, `Square(4)`, and `Cube(3)` share a list, and calling `get_area()` invokes the appropriate implementation for each object.
- A method inherited from `Square` makes `get_perimeter()` callable on `Cube`, but being callable does not guarantee that the method's result is semantically appropriate for a cube.
- A mixed collection raises an error if an object lacks the method being called; every object must provide that method directly or through inheritance.
- Defining a placeholder with `pass` prevents a missing-method error but returns `None`; returning `0` is an alternative when that value is suitable.
- The same polymorphic dispatch pattern works with dictionary values by iterating through `shapes.items()` and calling methods on each value.
Chapters
- A `shapes` list holds a `Cube(7)`, a `Square(4)`, and a `Cube(3)` together.
- A `for shape in shapes` loop calls `get_area()` on each object, and Python dispatches to the implementation for that object's class.
- The loop demonstrates polymorphism: the variable `shape` refers to different object types across iterations.
- Calling `get_perimeter()` works for `Cube` because it inherits the method from `Square`, though the inherited square perimeter may not be meaningful for a cube.
- Calling `get_volume()` fails on a `Square` because that class has no such method; the mixed-object loop raises an error when it reaches the square.
- Adding `get_volume()` to `Square` with `pass` prevents the missing-method error but returns `None`; returning `0` is another proposed placeholder.
- A dictionary stores `Cube` and `Square` instances under keys such as `cube1`, `square1`, and `cube2`.
- Iterating with `shapes.items()` provides each key and object, allowing calls such as `value.get_area()` to dispatch to the correct class method.
- The same method-availability requirement applies to dictionary values as to list elements; runtime type checks are unnecessary when objects support the called methods.
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.