温馨提示×

python子类怎么调用父类

小亿
101
2023-10-17 01:52:41
栏目: 编程语言

在Python中,可以使用super()函数来调用父类的方法。super()函数返回一个临时对象,该对象可以用于调用父类的方法。

以下是一个示例:

class ParentClass:
def __init__(self):
print("父类的初始化方法")
def some_method(self):
print("父类的方法")
class ChildClass(ParentClass):
def __init__(self):
super().__init__()  # 调用父类的初始化方法
def some_method(self):
super().some_method()  # 调用父类的方法
print("子类的方法")
child = ChildClass()
# 输出:
# 父类的初始化方法
child.some_method()
# 输出:
# 父类的方法
# 子类的方法

在上面的示例中,ChildClass继承自ParentClass。在ChildClass__init__方法中,可以使用super().__init__()来调用父类ParentClass__init__方法。在ChildClasssome_method方法中,可以使用super().some_method()来调用父类ParentClasssome_method方法。

0