[英]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
問題是你的__init__
有三個參數(包括self
),你在__add__
方法中只提供了兩個,因此__init__
的TypeError
:
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"
,這可能不是你想要的。
無論哪種方式,我相信你現在都能理解錯誤,並且你會修復它以獲得你想要的功能。
在__add__
方法中,您應該傳遞兩個參數; brand
缺失:
def __add__(self,other):
return Car('', self.cost+other.cost)
# ^^
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.