class vehicle:
def __init__(self,type):
self.type=type
def move(self):
print('交通工具可以移动')
class airplane(vehicle):
def __init__(self,type,color):
super().__init__(type) //super这种写法不会报错
self.color=color
def move(self):
print('飞机飞')
class train(vehicle):
def __init__(self,type,color):
super(vehicle, self).__init__(type) //super这种写法会报错
self.color=color
def move(self):
print('火车在铁轨上移动')
a1=airplane(111,222)
a1.move()
t1=train('火车','白色')
t1.move()
super(vehicle, self).__init__(type)
TypeError: object.__init__() takes exactly one argument (the instance to initialize)
这条语句super(vehicle, self).__init__(type) //super这种写法会报错
改为
super().__init__(type,color)
super() 方法的语法:
super(type[, object-or-type])
type -- 类。
object-or-type -- 类,一般是 self
它是从type的父类开始搜索,不包含type本身
所以应该是
super(train,self).__init__(type)
除非vehicle也有父类,
super(vehicle,self).__init__(type) 是调用vehicle的父类的init
class Par:
def __init__(self,a):
print("Par的init")
class vehicle(Par):
def __init__(self,type):
self.type=type
print("vehicle的init")
def move(self):
print('交通工具可以移动')
class train(vehicle):
def __init__(self,type,color):
super().__init__(type) #调用vehicle的init
super(vehicle,self).__init__(type) #调用Par的init
self.color=color
def move(self):
print('火车在铁轨上移动')
t1=train('火车','白色')
t1.move()
您好,我是有问必答小助手,你的问题已经有小伙伴为您解答了问题,您看下是否解决了您的问题,可以追评进行沟通哦~
如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~
ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632