Join Jungwoo Ryoo for an in-depth discussion in this video Working with inheritance and polymorphism, part of Python: Design Patterns.
- There are some additional key concepts to master in object oriented programming. We'll get started with inheritance. Inheritance establishes this relationship between two classes as parent and child. The child class keeps all the attributes and methods of its parent. It can also add new attributes or methods of its own to its definition. The child class can also override the existing methods of its parent.
For example, let's say that we have this pet class which has two child classes, one which is the dog class, and then the other which is the cat class. Both of these child classes share the common attribute which is the name attribute they're inheriting from the pet class. However, the child class is override their speak methods in their definition. For example, the dog class overrides his speak method to produce the barking sound, while the cat class overrides the same method to produce the meow sound.
Another object orientated class set important to understand is polymorphism. Polymorphism relies on inheritance and it allows the child classes to be instantiated and treated as the same type as its parent. In other words, polymorphism enables a parent class to be manifested into any of its child classes. For example, let's say that you're a user of this pet class and you don't know if the pet object is dog or cat until the runtime if you use polymorphism.
This is because the true nature of the object is hidden until the runtime, in this case, until this speak method is involved. So if the object is a dog object, you'll be producing the woof sound while the object will be producing the meow sound if the object happens to be the cat object. All the design patterns we cover in this course fully take advantage of these core object oriented programming concepts, therefore, it is a must for you to understand what classes, objects, inheritance, and polymorphism, before moving on.
- Understanding design patterns
- Best design practices: consistency, completeness, and correctness
- Working with creational patterns
- Working with structural patterns
- Working with behavioral patterns
Skill Level Intermediate
Q: In the strategy pattern example, why does the code keep executing the default function rather than the alternate?
A: The programming demonstration skips the step of defining what the strategy pattern should be when an alternate function name is provided
as an argument as shown below.