【问题标题】:Python Operator OverloadingPython 运算符重载
【发布时间】: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


【解决方案1】:

问题是您的__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",这可能不是你想要的。

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

【讨论】:

    【解决方案2】:

    在__add__ 方法中,您应该传递两个参数; brand 不见了:

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

    【讨论】:

      猜你喜欢
      • 2013-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多