在Python中,可以使用super()
函数来调用父类的构造函数。super()
函数返回一个临时对象,该对象允许你调用父类的方法。在构造函数中使用super()
函数调用父类的构造函数可以确保父类的属性被正确地初始化。
以下是一个示例,演示如何在子类的构造函数中调用父类的构造函数:
class ParentClass:
def __init__(self, arg1, arg2):
self.arg1 = arg1
self.arg2 = arg2
class ChildClass(ParentClass):
def __init__(self, arg1, arg2, arg3):
super().__init__(arg1, arg2) # 调用父类的构造函数
self.arg3 = arg3
在上面的示例中,ChildClass
继承自ParentClass
。在ChildClass
的构造函数中,使用super().__init__(arg1, arg2)
调用父类ParentClass
的构造函数,并传入相应的参数arg1
和arg2
。这样就可以确保子类和父类的属性都被正确地初始化。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
相关推荐:python如何调用父类构造函数