【已解决】TypeError: __init__() takes 1 positional argument but 3 were given

问题描述

TypeError: __init__() takes 1 positional argument but 3 were given

类型错误:__init__()函数需要1个参数,但给出了3个参数

问题分析

本人练习的代码中,其父类__init__()函数中的参数只有一个(个人原因少写了!),而在其子类实际调用的的参数需要三个,所以在调用的时候出现此类报错。

查找其他问题解决方法时,发现大概有以下错误原因导致此类相关报错:

1.函数传参时,父类或子类参数少些或多写,应都检查一遍(本人错误),例如,类初始化时__init__(self)只有一个参数,其子类的__init__(self,type,no,company)有三个参数,type和no是继承父类参数(附本人代码及修改后代码),在父类中type,no未写上。

2.函数书写错误,例如__init_(),__int__(),__init()等这些错误书写

代码检测

class Car(object):
    def __init__(self):
        self.type = type
        self.no = no
    def start(self):
        pass
    def stop(self):
        pass

class Taxi(Car):
    def __init__(self,type,no,company):
        super().__init__(type,no)
        self.company = company
    def start(self):
        print('乘客您好!')
        print(f'我是{self.company}出租车公司,我的车牌是{self.no},请问您要去哪里?')
    def stop(self):
        print('目的地到了,请您付款下车,欢迎再次乘坐!')

if __name__ == '__main__':
    taxi = Taxi('上海大众','京B8879','长城')
    taxi.start()
    taxi.stop()

 代码报错

TypeError: __init__() takes 1 positional argument but 3 were given

代码修改

对__init__()函数进行修改。

class Car(object):
    def __init__(self,type,no):
        self.type = type
        self.no = no
    def start(self):
        pass
    def stop(self):
        pass

成功解决问题。

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
青葱年少的头像青葱年少普通用户
上一篇 2023年11月29日
下一篇 2023年11月29日

相关推荐