欢迎访问宙启技术站
智能推送

类继承中super()方法的作用和用法

发布时间:2023-12-16 23:42:42

super()方法是在子类的构造函数中调用父类的构造函数,其作用是实现子类继承父类的属性和方法。

super()方法的用法一般有两种形式:

1. super()用在构造函数中,调用父类的构造函数,将父类的属性传给子类:

class ParentClass:
    def __init__(self, name):
        self.name = name
        
class ChildClass(ParentClass):
    def __init__(self, name, age):
        super().__init__(name)
        self.age = age

child = ChildClass("Tom", 10)
print(child.name)  # 输出:Tom
print(child.age)  # 输出:10

在这个例子中,ParentClass是父类,ChildClass是子类,子类的构造函数中调用了父类的构造函数,并添加了自己的属性age,通过super()方法将name属性传给了子类。

2. super()用于调用父类的方法:

class ParentClass:
    def say_hello(self):
        print("Hello, I am the parent class!")
        
class ChildClass(ParentClass):
    def say_hello(self):
        super().say_hello()
        print("Hello, I am the child class!")

child = ChildClass()
child.say_hello()

在这个例子中,父类和子类都有一个名为say_hello的方法,子类的方法使用super().say_hello()调用了父类的say_hello方法,从而实现了子类继承父类的方法。输出结果为:

Hello, I am the parent class!
Hello, I am the child class!

super()方法可以在多重继承中使用,它会按照继承的顺序依次调用每个父类的方法。例如:

class ClassA:
    def say_hello(self):
        print("Hello from ClassA!")

class ClassB:
    def say_hello(self):
        print("Hello from ClassB!")

class ClassC(ClassA, ClassB):
    def say_hello(self):
        super().say_hello()
        print("Hello from ClassC!")

class_c = ClassC()
class_c.say_hello()

在这个例子中,ClassC继承自ClassA和ClassB,它的say_hello方法中使用super().say_hello()调用了ClassA的say_hello方法,然后打印了自己的消息。输出结果为:

Hello from ClassA!
Hello from ClassC!

总之,super()方法的作用是实现子类继承父类的属性和方法,它可以在构造函数中调用父类的构造函数,并将父类的属性传给子类,也可以在方法中调用父类的方法。是实现类继承和重用代码的重要工具。