Python中Car类实例化触发TypeError:Car()不接受参数的原因
Python Car类构造错误分析与解决
问题重现
你编写的Car类代码如下:
class Car: def _init_(self,ma="",mo="",yr=0,p=0): self.make=ma self.model=mo self.year=yr self.price=p def _str_(self): res="" res += self.make res += " " res += self.model res += " " res += str(self.year) res += " " res += str(self.price) return res def applyDiscount(self,rate): newPrice=self.price-self.price*rate self.price=newPrice return self.price myCar=Car("Dodge","Caravan", 2021,3000) print(myCar.applyDiscount(.12)) other=Car("subaru","Legacy",2007,300) print(myCar) print(other)
运行时触发错误:
Traceback (most recent call last):
File "", line 38, in
TypeError: Car() takes no arguments
错误原因
- 构造函数命名错误:Python规定类的构造函数必须是
__init__(前后各两个下划线),你写成了_init_(仅一个下划线),Python无法识别这个方法为构造函数,会使用默认的无参构造,因此创建对象传参时会报错。 - 字符串格式化方法命名错误:
_str_同样需要改为__str__,否则打印对象时不会执行你自定义的格式化逻辑,会输出默认的对象内存地址。
修正后的代码
class Car: # 修正为__init__(双下划线) def __init__(self,ma="",mo="",yr=0,p=0): self.make=ma self.model=mo self.year=yr self.price=p # 修正为__str__(双下划线) def __str__(self): res="" res += self.make res += " " res += self.model res += " " res += str(self.year) res += " " res += str(self.price) return res def applyDiscount(self,rate): newPrice=self.price-self.price*rate self.price=newPrice return self.price myCar=Car("Dodge","Caravan", 2021,3000) print(myCar.applyDiscount(.12)) # 输出:2640.0 other=Car("subaru","Legacy",2007,300) print(myCar) # 输出:Dodge Caravan 2021 2640.0 print(other) # 输出:subaru Legacy 2007 300
内容的提问来源于stack exchange,提问作者Meg123
相关产品推荐
相关产品推荐

