Inheritance, calling, and parameter passing of subclasses and parent classes in Python

1.Inheritance

In Python, the relationship between subclasses and parent classes is achieved through inheritance. Inheritance allows subclasses to inherit the properties and methods of the parent class, and can also add new properties and methods to the subclass, or override the methods of the parent class.

Here is a simple example that shows how to create a parent class and a child class, and inherit and extend the functionality of the parent class in the child class:

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

    def speak(self):
        print(f"{self.name} made a sound.")

# Define a subclass that inherits from Animal class
class Dog(Animal):
    def __init__(self, name, breed):
        # Call the constructor of the parent class
        super().__init__(name)
        self.breed = breed

    def speak(self):
        # Call the parent class method
        super().speak()
        print("Woof woof woof!")

    def fetch(self):
        print(f"{self.name} is chasing the ball.")

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

#Create an instance of a subclass
dog = Dog("Puppy", "Corgi")
dog.speak()
dog.fetch()

2. Call

To call functions of the parent class in a subclass, you can use super() to access and call the methods of the parent class. Here is an example:

class Parent:
    def __init__(self):
        self.name = "Parent"

    def greet(self):
        print("Hello from", self.name)

class Child(Parent):
    def __init__(self):
        super().__init__()
        self.name = "Child"

    def greet(self):
        super().greet()
        print("Nice to meet you!")

#Create subclass instance
child = Child()
child.greet()

Output:

Hello from Child
Nice to meet you!

In the above example, the Child class inherits from the Parent class. The __init__ method in the subclass Child uses super().__init__() to call the constructor of the parent class Parent Function to initialize the name attribute.

In the greet method in the subclass Child, we first use super().greet() to call the parent class Parent code>’s greet method, thereby printing “Hello from Child”. Then, we added an additional print statement in the greet method of the subclass to print “Nice to meet you!”.

By using super(), we can call functions of the parent class in the subclass. In this way, you can extend the function of the parent class method in the subclass, or use the parent class method in the subclass to perform specific operations. In the example, the subclass Child adds its own extra print statement after calling the parent class’s greet method.

3. Passing parameters

There are two classes FasterRCNNBase and FasterRCNN, where FasterRCNN is a subclass of FasterRCNNBase. If you want to call the constructor of the parent class FasterRCNNBase in the constructor of FasterRCNN, replace backbone, rpn, roi_heads and transform are passed as parameters to the parent class. The code example is as follows:

class FasterRCNNBase(nn.Module):
    def __init__(self, backbone, rpn, roi_heads, transform):
        super(FasterRCNNBase, self).__init__()
        # Perform initialization or other operations in the parent class constructor
        #...


class FasterRCNN(FasterRCNNBase):
    def __init__(self, backbone, num_classes=None):
        super(FasterRCNN, self).__init__(backbone, rpn, roi_heads, transform)
        # Perform additional initialization or other operations in the subclass constructor
        # ...

In the constructor of FasterRCNN, we call the parent class FasterRCNNBase using the method of super(FasterRCNN, self).__init__(backbone, rpn, roi_heads, transform) ‘s constructor, passing backbone, rpn, roi_heads and transform as parameters to the parent Class constructor.

In this way, when you instantiate the FasterRCNN class, the constructor of the parent class FasterRCNNBase will be called, the initialization operation will be performed, and the subclass FasterRCNN ‘s constructor can also perform additional initialization or other operations if needed.

Change super(FasterRCNN, self).__init__(backbone, rpn, roi_heads, transform) to super().__init__(backbone, rpn, roi_heads, transform) No There is a substantial difference because the FasterRCNN class does not have multiple inheritance.

In the case of single inheritance, super().__init__(...) will automatically determine the parent class and call its constructor without explicitly specifying the name of the parent class. Therefore, super(FasterRCNN, self).__init__(backbone, rpn, roi_heads, transform) and super().__init__(backbone, rpn, roi_heads, transform) are here are equivalent in both cases.

In the case of multiple inheritance, the usage of super() is different. When a class has multiple parent classes, super() is used to specify the next class in the inheritance chain and call the methods of that class.

In multiple inheritance, each parent class can call the methods of its next parent class in the inheritance chain through super(). This ensures that methods are called in the correct order and avoids repeated or missed calls.

The following is an example of multiple inheritance, showing the role of super() in multiple inheritance:

class ParentA:
    def __init__(self):
        print("ParentA")

class ParentB:
    def __init__(self):
        print("ParentB")

class Child(ParentA, ParentB):
    def __init__(self):
        super().__init__() # Call the constructor of the next parent class
        print("Child")

#Create subclass instance
child = Child()

Output:

ParentB
ParentA
Child

In the above example, the Child class inherits both the ParentA and ParentB parent classes. In the constructor of the subclass Child, we use the super().__init__() method to call the constructor of the next parent class ParentB function, and then call the constructor of the parent class ParentA.

By using super(), the correct calling order of parent class constructors is ensured, and parameters can be passed correctly and initialization operations performed even in inheritance chains of multiple parent classes.

It should be noted that when using super() in multiple inheritance, the order in which methods are called depends on the order in which the classes are defined. In the above example, the Child class inherits first from ParentA and then from ParentB. Therefore, the constructor of ParentB is called first, then the constructor of ParentA, and finally the constructor of the Child class itself.

To use super() in multiple inheritance and pass parameters to ParentA, this can be achieved by passing parameters in the super() call. Here is an example:

class ParentA:
    def __init__(self, param_a):
        print("ParentA:", param_a)

class ParentB:
    def __init__(self):
        print("ParentB")

class Child(ParentA, ParentB):
    def __init__(self, param_a, param_b):
        super().__init__(param_a) # Pass parameters to ParentA
        print("Child:", param_b)

#Create subclass instance
child = Child("Hello", "World")

Output:

ParentB
ParentA: Hello
Child: World

In the above example, the constructor of class ParentA accepts a parameter param_a, which we want to pass in the constructor of subclass Child ParentA. To do this, we can pass the parameter param_a in the super() call.

In the constructor of the subclass Child, we use super().__init__(param_a) to call the next parent class ParentA Constructor and pass param_a as parameter to it.

This way, when creating an instance of the Child class, we can pass the required parameters for both the ParentA and Child classes. In the above example, we create an instance through Child("Hello", "World"), passing the string “Hello” as the parameter of ParentA and passing the string “World” as a parameter of the Child class.

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. Python entry skill treeBasic Grammar Category 352602 people are learning the system