【发布时间】:2015-11-15 12:38:52
【问题描述】:
我在 Python 中重载添加运算符时遇到问题。 每次我尝试超载它时,我都会得到:
TypeError: __init__() takes exactly 3 arguments (2 given)
这是我的代码:
class Car:
carCount = 0
def __init__(self,brand,cost):
self.brand = brand
self.cost = cost
Car.carCount +=1
def displayCount(self):
print "Number of cars: %d" % Car.carCount
def __str__(self):
return 'Brand: %r Cost: %d' % (self.brand, self.cost)
def __del__(self):
class_name = self.__class__.__name__
print class_name,'destroyed'
def __add__(self,other):
return Car(self.cost+other.cost)
c=Car("Honda",10000)
d=Car("BMW",20000)
print c
a= c+d
【问题讨论】:
-
return Car(self.cost+other.cost)。你缺少品牌,但我想你想要return self.cost+other.cost -
这样添加汽车真的没有意义;一辆车加一辆车不也是一辆车!
-
当你将两辆车相加时,
brand的结果是什么?
标签: python operators overloading typeerror