Python define a subclass inheriting from a parent class, and override a method in the subclass

Document 对象参考手册Python3 Examples

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()

Code explanation:

  1. Animalis a parent class, which defines aspeakmethod that outputs "Animal speaks".
  2. DogYesAnimalis a subclass of , it inheritsAnimalall attributes and methods of .
  3. InDogIn the class, we override thespeakmethod, making it output "Dog barks".
  4. Create theAnimalclass objectanimal, and call thespeakmethod, which outputs "Animal speaks".
  5. Create theDogclass objectdog, and call thespeakmethod, which outputs "Dog barks".

Output result:

Animal speaks
Dog barks

Document 对象参考手册Python3 Examples

Other extensions