Python 运算符重载

Python Operator Overloading

我在 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

__add__方法中,你应该传递两个参数; brand 缺失:

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

问题是您的 __init__ 需要三个参数(包括 self)而您在 __add__ 方法中只提供了两个参数,因此 TypeError __init__:

TypeError: __init__() takes exactly 3 arguments (2 given)

因此,在您的 __add__ 中,您应该添加(没有双关语意) brand 参数:

def __add__(self, other):
    return Car(self.brand+other.brand, self.cost+other.cost)

所以在这种情况下您会得到一个 "Honda BMW",这可能不是您想要的。

无论哪种方式,我相信您现在已经理解了错误,您将修复它以获得您想要的功能。