温馨提示×

python中的super函数怎么使用

小亿
91
2023-12-21 23:26:47
栏目: 编程语言

在Python中,super()函数用于调用父类的方法。它可以在子类的方法中调用父类的同名方法,实现方法的覆盖和扩展。super()函数接受两个参数:子类的类名和子类的对象。它的使用格式为:

super(子类类名, 子类对象)

在子类的方法中使用super()函数时,可以在子类方法中调用父类的同名方法,并传递必要的参数。例如:

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

    def say_hello(self):
        print("Hello,", self.name)

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

    def say_hello(self):
        super().say_hello()
        print("I'm", self.age, "years old")

child = ChildClass("Alice", 10)
child.say_hello()

输出结果为:

Hello, Alice
I'm 10 years old

在上面的例子中,ChildClass继承自ParentClass,并重写了say_hello方法。在ChildClass__init__方法中,使用super().__init__(name)调用了父类的__init__方法,确保了子类对象的初始化。在ChildClasssay_hello方法中,使用super().say_hello()调用了父类的say_hello方法,然后再添加了自己的逻辑。这样,子类对象调用say_hello方法时,既可以执行父类的方法,又可以执行子类的方法。

0