Python中的继承

Makerr / 2024-10-13 / 原文

1、基本继承

  子类在定义时将父类作为参数传递即可

class Parent:  # 定义父类
    def __init__(self, name):
        self.name = name

    def greet(self):
        return f"Hello, {self.name}"
        

class Child(Parent):  # 定义子类,继承自 Parent
    def __init__(self, name, age):
        super().__init__(name)  # 调用父类的构造方法
        self.age = age

    def introduce(self):
        return f"I am {self.name}, and I am {self.age} years old."

if __name__=="__main__":
    child = Child("Alice", 12)
    print(child.greet())      # 调用了从 Parent 继承的 greet 方法
    print(child.introduce())  # 调用了 Child 自己的 introduce 方法

  子类继承了父类的greet方法。同时,子类定义了一个新的方法introduce


2、super关键字

  super关键字用于调用父类中的方法或者属性的函数,常见用法是在子类中调用父类的构造函数(__init__方法)来初始化父类的属性

class Child(Parent):  # 定义子类,继承自 Parent
    def __init__(self, name, age):
        super().__init__(name)  # 调用父类的__init__方法,确保从父类的属性被正确初始化
        self.age = age

  使用super可以避免直接饮用父类的名字,从而使得代码更加灵活