Python Create a Subclass Using Inheritance

Document 对象参考手册Python3 Examples

In Python, inheritance is an important feature of object-oriented programming. Through inheritance, a subclass can inherit the attributes and methods of a parent class, and can add new attributes and methods in the subclass, or override the methods of the parent class. The following is a simple example showing how to use inheritance to create a subclass.

Example

# Define a parent class
class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return f"{self.name} makes a sound."

# Define a subclass, inheriting from Animal
class Dog(Animal):
    def speak(self):
        return f"{self.name} barks."

# Create an instance of the parent class
animal = Animal("Generic Animal")
print(animal.speak())

# Create an instance of the subclass
dog = Dog("Buddy")
print(dog.speak())

Code explanation:

  1. Animalis a parent class, it has a constructor__init__, used to initializenameattribute.speakmethod returns a string representing the sound made by the animal.
  2. Dogis a subclass, inheriting fromAnimal. It overrides thespeakmethod, returning a string representing a dog's bark.
  3. Created an instance of theAnimalclassanimal, and called thespeakmethod, output "Generic Animal makes a sound.".
  4. Created an instance of theDogclassdog, and called thespeakmethod, output "Buddy barks.".

Output result:

Generic Animal makes a sound.
Buddy barks.

Document 对象参考手册Python3 Examples

Other Extensions