super函数解析

91 阅读1分钟

使用条件

super常使用于子类中,且子、父类都有相同的方法,需要在子类同时调用父类方法。

调用方法

super.method()

常用方法

super().__init__()

说明: 在调用子类的构造方法时,需要调用父类的构造方法的时候,可以使用

class ParentClass:
    def method(self):
        print("ParentClass method")

class ChildClass(ParentClass):
    def method(self):
        super().method()  # 调用父类的方法
        print("ChildClass method")

child_obj = ChildClass()
child_obj.method()

参数说明

将子类的属性值通过参数给父类变量

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

class ChildClass(ParentClass):
    def __init__(self, name, age):
        super().__init__(name)  # 调用父类的构造函数并传递参数
        self.age = age

child_obj = ChildClass("John", 25)
print(child_obj.name)  # 输出:"John"
print(child_obj.age)  # 输出:25

super(email_logit, self) 内带的参数说明

email_logit:子类的类对象、类名 self:子类的实例对象

注意:尽量不要带参数,这样容易把代码写死,不利于维护

引用:

image.png

image.png

image.png