酷代码 AI
菜单
服务商

Python 开发必知:面向对象中 super 函数调用父类方法的奥秘

在Python中,`super()`是一个内置函数,用于调用父类的方法。它的主要作用是在子类方法中调用父类的方法。 在继承中,子类通常会重写父类的一些方法。如果需要调用父类的方法,可以使用`super()`函数。`super()`函数会返回一个指向父类对象的引用,然后就可以像调用子类方法一样调用父类的方法。 例如: ```python class Parent: def __init__(self, name): self.name = name def say_hello(self): print(f"Hello, my name is {self.name}.") class Child(Parent): def __init__(self, name): super().__init__(name) def say_hello(self): super().say_hello() print(f"Hi, my name is {self.name}.") child = Child("Alice") child.say_hello() ``` 在这个例子中,`Child`类继承了`Parent`类。`Child`类重写了`say_hello`方法。在`Child`类的`say_hello`方法中,使用`super().say_hello()`调用了父类的`say_hello`方法。这样,当`Child`类的`say_hello`方法被调用时,会先打印出"Hello, my name is Alice.",然后再打印出"Hi, my name is Alice."。 ######[AI写代码神器 | 296点数解答 | 2023-11-08 00:52:25]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]