温馨提示×

python如何调用父类构造函数

九三
1023
2021-01-26 18:35:57
栏目: 编程语言

python如何调用父类构造函数

python中使用super函数调用父类构造函数,具体方法如下:

1.首先,在python项目中,定义一个Adata类,并创建一个__init__构造函数;

class Adata

def __init__(self,num):

self,num = num

2.Adata类定义好后,在Adata类中定义一个showNum类方法,并打印self.num;

class Adata

def __init__(self,num):

self,num = num

def showNum(self):

print(self.num)

3.在定义一个Bdata类,并创建构造函数,传入type和sun参数;

class Adata

def __init__(self,num):

self,num = num

def showNum(self):

print(self.num)

class Bdata:

def __init__(self,type,sun)

self.type = type

self.sum = sum

4.最后,定义一个Cdata类,继承父类Adata和Bdata,使用super函数即可调用父类的构造函数;

class Adata

def __init__(self,num):

self,num = num

def showNum(self):

print(self.num)

class Bdata:

def __init__(self,type,sun)

self.type = type

self.sum = sum

class Cdata(Adata,Bdata):

def __init__(self,num,type,sun):

super.__init__(num)

super.(Cdata,self).__init__(num)

Bdata.__init__(self,type,sun)

0