Classes and inheritance
__init__(self, ...) is Python's constructor - it runs automatically when you
create an instance, and it's where you set the instance's own data with
self.attribute = value. Methods defined in the class body are shared by
every instance instead of copied onto each one; self is how a method reaches
back into the specific instance it was called on.
class Dog(Animal): builds a subclass - Dog gets every method Animal has
for free, and only needs to define what's different. Overriding a method -
writing a same-named method in the subclass - replaces the parent's version
for instances of the subclass, without touching how Animal itself behaves.
super().__init__(...) lets a subclass reuse the parent's constructor instead
of duplicating it, though this lesson's Dog doesn't need its own __init__
at all - it can just inherit Animal's.
Your task: write class Animal with __init__(self, name) storing
self.name, and a method speak(self) returning f"{self.name} makes a sound". Then write class Dog, extending Animal, that overrides speak()
to return f"{self.name} barks" instead.
You'll practice:
Writing __init__ and a method on a class
Subclassing with inheritance and overriding one method
Show a hint
Show solution
Related reading: What OOP Actually Is →
Previous Next