TypeError:Car()不接受任何参数 [英] TypeError: Car() takes no arguments

查看:63
本文介绍了TypeError:Car()不接受任何参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个类.但是在运行代码时出现此错误:

I am trying to create a class. But while running the code I am getting this error:

TypeError:Car()不接受任何参数.

TypeError: Car() takes no arguments.

class Car:
   def __rep__(self):
        return f'Car({self.name},{self.year_built},{self.model})'


c1 = Car('minicooper','1970','MX1')

推荐答案

您的程序缺少构造函数,因此出错.另请注意,您可能指的是 __ repr __ ,而不是 __ rep __ .您的最终代码应如下所示-

Your program is missing constructor and hence the error. Also do note that you are probably referring to __repr__ and not __rep__. You final code should look something like this -

class Car: 
    # In your code, this constructor was not defined and hence you were getting the error
    def __init__(self,name,year,model):
        self.name = name
        self.year_built = year
        self.model = model
    def __repr__(self):
        return f'Car({self.name},{self.year_built},{self.model})'

# The below statement requires a constructor to initialize the object
c1 = Car('minicooper','1970','MX1')

#
print(c1)

输出:

>>> Car(minicooper,1970,MX1)

__ init __ 在python中用作构造函数.用于初始化对象的状态.构造函数的任务是在创建类的对象时向类的数据成员初始化(分配值).因此,当您在调用中传递变量- Car('minicooper','1970','MX1')时,将调用构造函数.您没有构造函数,因此收到错误消息.

The __init__ is used in python as constructor. It is used to initialize the object’s state. The task of constructors is to initialize(assign values) to the data members of the class when an object of class is created. So, when you pass the variables in your call - Car('minicooper','1970','MX1'), the constructor is called. You didn't had a constructor and hence you were getting the error message.

__ repr __(object)用于返回包含对象可打印表示形式的字符串.当您尝试打印对象时,将使用它.您在代码中错误地将其称为 __ rep __ .我已经在上面的代码中对其进行了纠正.

__repr__(object) is used to return a string containing a printable representation of an object. This will be used when you are trying to print the object. You had incorrectly mentioned it as __rep__ in your code. I have corrected it in the code above.

希望这会有所帮助!

这篇关于TypeError:Car()不接受任何参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆