Linux 拨号vps windows公众号手机端

python调用父类构造函数的方法是什么

lewis 7年前 (2018-04-28) 阅读数 9 #程序编程
文章标签 python

在Python中,可以使用super()函数来调用父类的构造函数。通过super()函数,可以获得父类的对象,并调用父类的方法。在子类的构造函数中,可以使用super().__init__()来调用父类的构造函数。示例代码如下:

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
child = ChildClass(arg1_value, arg2_value, arg3_value)

在上述示例中,ChildClass继承自ParentClass。在ChildClass的构造函数中,通过super().__init__(arg1, arg2)调用了ParentClass的构造函数,并传入所需的参数。这样可以保证在创建ChildClass对象时,父类的构造函数也会被调用。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门