Skip to main content
 首页 » 编程设计

python之Python 和构造函数中的多重继承

2024年10月25日13zlslch

<分区>

我正在学习python,正在学习类和对象。我对此代码有疑问

class machine(object): 
    def __init__(self,processor): 
        print "I am in constructor of machine class" 
        print processor 
 
class computer(machine): 
    def __init__(self,name,processor): 
        print "I am in constructor of computer class" 
        super(computer,self).__init__(processor) 
        print name, 
        print processor 
 
class laptop(machine): 
    def __init__(self,name,processor): 
        print "I am in constructor of laptop class" 
        super(laptop,self).__init__(processor) 
        print name, 
        print processor 
 
class respbarry(computer,laptop): 
    def __init__(self,name,processor): 
        print "I am in constructor of respbarry class" 
        super(respbarry,self).__init__(name,processor) 
        print name, 
        print processor 
 
m = machine("P4") 
c = computer("Computer","P4") 
l = laptop("Laptop","P4") 
r = respbarry("Respbarry","P4") 

现在做上面我得到的错误是

I am in constructor of machine class  
P4 
I am in constructor of computer class 
I am in constructor of machine class  
P4 
Computer P4 
I am in constructor of laptop class 
I am in constructor of machine class  
P4 
Laptop P4 
I am in constructor of respbarry class 
I am in constructor of computer class 

所以当我调用机器类时,我得到机器调用的机器构造函数,然后我调用计算机类构造函数,然后调用笔记本电脑类构造函数。到目前为止一切都很好,但在 respbarry 构造函数中我收到错误?我认为机器类构造函数在 respbarry 中应该是 2 次,但我收到错误 TypeError: __init__() 正好接受 3 个参数(给定 2 个)