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)
我希望这有帮助
您的程序缺少构造函数,因此出现错误。还要注意,您可能指的是
__repr__
,而不是__rep__
。最终的代码应该是这样的-输出:
__init__
在python中用作构造函数。它用于初始化对象的状态。构造函数的任务是在创建类的对象时初始化(赋值)类的数据成员。因此,当您在调用中传递变量-Car('minicooper','1970','MX1')
时,将调用构造函数。您没有构造函数,因此会收到错误消息__repr__(object)
用于返回包含对象的可打印表示形式的字符串。当您试图打印对象时,将使用此选项。您在代码中错误地将其称为__rep__
。我已经在上面的代码中更正了它希望这有帮助
相关问题 更多 >
编程相关推荐