Reputation: 573
I have a problem with overloading adding operator in Python. Everytime I try to overload it i get:
TypeError: __init__() takes exactly 3 arguments (2 given)
Here is my code:
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
Upvotes: 1
Views: 126
Reputation: 160377
The problem is that your __init__
takes three arguments (including self
) and you have supplied just two in your __add__
method, hence the TypeError
for __init__
:
TypeError: __init__() takes exactly 3 arguments (2 given)
So in your __add__
you should add (no pun intended) the brand
argument:
def __add__(self, other):
return Car(self.brand+other.brand, self.cost+other.cost)
So you'll get a "Honda BMW"
in this case which probably isn't what you want.
Either way, I'm sure you understand the error now and you'll fix it to get the functionality you want.
Upvotes: 2
Reputation: 368944
In the __add__
method, you should pass two arguments; brand
is missing:
def __add__(self,other):
return Car('', self.cost+other.cost)
# ^^
Upvotes: 1