1

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
3
  • return Car(self.cost+other.cost). you are missing brand but I imagine you want return self.cost+other.cost Commented Nov 15, 2015 at 12:40
  • 2
    It doesn't really make sense to add cars like that; a car plus a car isn't also a car! Commented Nov 15, 2015 at 12:47
  • When you add two cars together, what's the resulting brand? Commented Nov 15, 2015 at 12:52

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

In the __add__ method, you should pass two arguments; brand is missing:

def __add__(self,other):
    return Car('', self.cost+other.cost)
    #          ^^

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.