To write a Python program that demonstrates class inheritance by creating a parent class Fish with a method type, and a child class Shark that overrides the type method.
- Define the
Fishclass with a method namedtype()that prints"fish". - Define the
Sharkclass as a subclass ofFish, and override thetype()method to print"shark". - Create an instance of the
Fishclass namedobj_goldfish. - Create an instance of the
Sharkclass namedobj_hammerhead. - Use a
forloop to iterate over both objects. - Within the loop, call the
type()method using the loop variable. - Output will demonstrate method overriding: printing
"fish"and"shark"accordingly.
class Fish:
def type(self):
print("fish")
class Shark(Fish):
def type(self):
print("shark")
obj_goldfish=Fish()
obj_hammerhead=Shark()
for animal in(obj_goldfish,obj_hammerhead):
animal.type()
Thus the program has been successfully executed.