Python Class Inheritance and Polymorphism
In Object-Oriented Programming (OOP), when defining a class, you can inherit from an existing class. The new class is called a Subclass, and the inherited class is called a Base class, Parent class, or Super class.
Format:
SubclassName(ParentClassName):
pass
Usage Example
class Animal(object):
def run(self):
print('Animal is running...')
class Dog(Animal):
pass
class Dog1(Animal):
def run(self):
print('Dog is running...')
def run_twice(animal):
animal.run()
animal.run()
dog = Dog()
dog.run() # Output: Animal is running...
dog1 = Dog1()
dog1.run() # Output: Dog is running..., executes the subclass's own method
run_twice(Animal())
# Output: Animal is running...
# Output: Animal is running...
run_twice(Dog1())
# Output: Dog is running...
# Output: Dog is running...
# Add a new subclass Tortoise, then call the run_twice function, it still works
class Tortoise(Animal):
def run(self):
print('Tortoise is running slowly...')
run_twice(Tortoise()) # Calling run_twice function, it still works, just ensure the passed object has a run() method
# Output: Tortoise is running slowly...
# Output: Tortoise is running slowly...