classAnimal:
def__init__(self, name):
self.name = name
defspeak(self):
returnf"{self.name} makes a sound"classCat(Animal):
defspeak(self):
returnf"{self.name} says Meow!"classDog(Animal):
defspeak(self):
returnf"{self.name} says Woof!"
animals = [Cat("Whiskers"), Dog("Rex"), Animal("???")]
for a in animals:
print(speak())
print(f" Is Animal? {isinstance(a, Animal)}")
Output
Click "Run" to execute your code
Subclasses inherit from a parent and can override methods. isinstance() checks the full hierarchy.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?