class x:
def __init__(self,name):
self.name=name
def __str__(self):
return self.name
def __cmp__(self,other):
print("cmp method called with self="+str(self)+",other="+str(other))
return self.name==other.name
# return False
instance1=x("hello")
instance2=x("there")
print(instance1==instance2)
print(instance1.name==instance2.name)
輸出是:__cmp__方法在Python 2.x中沒有像預期的那樣工作?這裏
cmp method called with self=hello,other=there
True
False
這是不是我所期待的:我想說「兩個實例都是平等的,如果名字字段相等」。
如果我只是從__cmp__
功能return False
,這也報告爲True
! 如果我返回-1
,那麼我得到False
- 但由於我試圖比較字符串,這不正確。
我在這裏做錯了什麼?
Thankyou - 你會得到蜱蟲(儘管其他人提供了類似的信息),因爲這是最清楚的解釋! – monojohnny 2010-01-27 12:41:23
正如其他人所評論的,__cmp __()已過時。定義__lt __(),__eq __()和__gt __()來代替。按照http://docs.python.org/dev/whatsnew/3.0.html#ordering-comparisons – smci 2011-06-30 03:51:31