SoFunction
Updated on 2025-04-11

Methods for subclasses to inherit parent class to pass parameters in Python

1. Basic concepts

  • Parent class (base class): Inherited class.
  • Subclass (derived class): Inheriting the class that is the parent class.

2. Realize inheritance

In Python, subclasses inherit the syntax of parent class is very straightforward. Here is a simple example:

class Parent:
    def __init__(self, value):
         = value

class Child(Parent):
    pass

In this example,ChildClass inheritedParentkind.

3. Pass parameters

When a child class inherits the parent class, it is usually necessary to pass parameters to the parent class's constructor. This can be done by subclassing__init__The parent class in the method__init__Method implementation.

class Child(Parent):
    def __init__(self, value, child_value):
        super().__init__(value)
        self.child_value = child_value

Here, super().__init__(value) calls the constructor of the parent class and passes the necessary parameters. The super() function is a method used to call the parent class (superclass).

4. Overwrite parent class method

Subclasses can override methods of parent classes to provide subclass-specific behavior. When these methods are called, the version defined in the subclass is run instead of the version in the parent class.

class Child(Parent):
    def __init__(self, value, child_value):
        super().__init__(value)
        self.child_value = child_value

    def display_value(self):
        print(f"Parent Value: {}, Child Value: {self.child_value}")

5. Multiple inheritance

Python also supports multiple inheritance, and a subclass can inherit multiple parent classes.

class Parent2:
    def __init__(self, value2):
        self.value2 = value2

class Child(Parent, Parent2):
    def __init__(self, value, value2, child_value):
        Parent.__init__(self, value)
        Parent2.__init__(self, value2)
        self.child_value = child_value

In this example,ChildClasses inherited at the same timeParentandParent2kind.

6. Use examples

We use a concrete example to illustrate how a subclass overrides the parent class's methods and how to implement multiple inheritance

Example 1: Override the parent class method

First, we define a parent classAnimal, it has a methodspeak, then we define a subclassDog, it overrides the parent class'sspeakmethod.

class Animal:
    """Animals"""

    def speak(self):
        """Make an animal's sound"""
        return "An animal's voice"

class Dog(Animal):
    """Dogs, inherit animals"""

    def speak(self):
        """Methods that overwrite the parent class, make the dog's barking"""
        return "Wow!"

In this example, when we createDogInstance of the class and callspeakWhen the method is used, "Woom!" will be output instead of "an animal sound".

Example 2: Multiple Inheritance

Next, we define two parent classesFatherandMother, and a subclass that inherits these two classesChild

class Father:
    """Father's Class"""
    
    def hobby(self):
        """Father's Hobbies"""
         return "Father likes fishing"

 class Mother:
     """Mother's Class"""

    def hobby(self):
        """Mother's hobbies"""
        return "Mother likes gardening"

class Child(Father, Mother):
    """Child class inherits from father and mother"""

    def hobby(self):
        """Methods to overwrite parent class to show children's interests and hobbies"""
        return f"The child combines the interests and hobbies of two parents:{(self)} and {(self)}"

In this example,ChildClass inheritedFatherandMotherkind. When calledChildClassichobbyWhen it comes to method, it will combine the interests and hobbies of the two parent classes.

Test code and output results

Now let's create instances of these classes and test their methods.

# Create Animal and Dog instancesanimal = Animal()
dog = Dog()

# Create an instance of Childchild = Child()

# Test the method and print the output resultprint(())  # The sound of an animalprint(())     # Wool!
print(())   # The child combines two parental hobbies: father likes fishing and mother likes gardening

This code will create instances of several classes, call their methods, and then print out the results. We can see that subclassDogOverwrite the parent classAnimalofspeakMethod, andChildThe class combines its two parent classesFatherandMotherofhobbymethod.

7. Conclusion

Inheritance is one of the core concepts of object-oriented programming. In Python, the inheritance mechanism can easily extend and modify the functions of a class. Correct use of inheritance can make the code clearer and more reusable.

The above is the detailed content of the method of subclasses in Python that inherit the parent class to pass parameters. For more information about Python subclasses inherit the parent class to pass parameters, please pay attention to my other related articles!