在Python中,super()函数用于调用父类(超类)的方法。这在子类需要扩展或修改父类的方法时非常有用。以下是如何使用super()调用父类方法的步骤:
class Parent:
def __init__(self):
self.name = "Parent"
def say_hello(self):
print(f"Hello, I am {self.name}")
__init__方法中,使用super()调用父类的__init__方法。在子类中定义一个新方法或重写父类的方法,并在其中使用super()调用父类的相应方法。例如:class Child(Parent):
def __init__(self):
super().__init__() # 调用父类的__init__方法
self.name = "Child"
def say_hello(self):
super().say_hello() # 调用父类的say_hello方法
print(f"I am {self.name}")
child = Child()
child.say_hello()
输出结果:
Hello, I am Parent
I am Child
在这个例子中,Child类继承了Parent类。我们使用super()在Child类的__init__方法中调用了Parent类的__init__方法,以确保父类的初始化代码被执行。然后,我们在Child类中重写了say_hello方法,并在其中使用super()调用了Parent类的say_hello方法。这样,我们可以保留父类方法的实现,并在其基础上添加子类的特定行为。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。