Python define a subclass inheriting from a parent class, and override a method in the subclass
In Python, we can define a subclass to inherit from a parent class, and override the parent class's methods in the subclass. The subclass can inherit all attributes and methods of the parent class, and can also override the parent class's methods as needed to implement different functionality.
Example
# Define a parent class
class Animal:
def speak(self):
print("Animal speaks")
# Define a subclass that inherits from the parent class
class Dog(Animal):
# Override the parent class's speak method
def speak(self):
print("Dog barks")
# Create a parent class object
animal = Animal()
animal.speak()
# Create a subclass object
dog = Dog()
dog.speak()
class Animal:
def speak(self):
print("Animal speaks")
# Define a subclass that inherits from the parent class
class Dog(Animal):
# Override the parent class's speak method
def speak(self):
print("Dog barks")
# Create a parent class object
animal = Animal()
animal.speak()
# Create a subclass object
dog = Dog()
dog.speak()
Code explanation:
Animalis a parent class, which defines aspeakmethod that outputs "Animal speaks".DogYesAnimalis a subclass of , it inheritsAnimalall attributes and methods of .- In
DogIn the class, we override thespeakmethod, making it output "Dog barks". - Create the
Animalclass objectanimal, and call thespeakmethod, which outputs "Animal speaks". - Create the
Dogclass objectdog, and call thespeakmethod, which outputs "Dog barks".
Output result:
Animal speaks Dog barksOther extensions
Python3 Examples