2010-01-27 76 views
5
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 - 但由於我試圖比較字符串,這不正確。

我在這裏做錯了什麼?

回答

9

__cmp__(x,y)應該返回一個負數(如-1)如果x < y,一個正數(如1)如果x > y和0如果x == y。你不應該返回一個布爾值。

你超載的是__eq__(x, y)

+0

Thankyou - 你會得到蜱蟲(儘管其他人提供了類似的信息),因爲這是最清楚的解釋! – monojohnny 2010-01-27 12:41:23

+0

正如其他人所評論的,__cmp __()已過時。定義__lt __(),__eq __()和__gt __()來代替。按照http://docs.python.org/dev/whatsnew/3.0.html#ordering-comparisons – smci 2011-06-30 03:51:31

2

__cmp__()已過時。改爲定義__lt__(),__eq__()__gt__()

即便如此,你做錯了。你應該返回一個整數。

+0

「過時」?你從哪裏挑選的?其他的存在,但在大多數情況下,使用__cmp__更有意義,在這種情況下,例如,它需要3個方法而不是一個。 http://docs.python.org/reference/datamodel.html – jsbueno 2010-01-27 11:07:05

+1

@jsbueno:第三項要點:http://docs.python.org/dev/3.0/whatsnew/3.0.html#ordering-comparisons – 2010-01-27 11:11:50

+0

URL已移動到http://docs.python.org/dev/whatsnew/3.0.html#ordering-comparisons – smci 2011-06-30 03:49:25

5

__cmp__方法應該返回-1,0或1,當自己<其他時,自己==其他,自己>別的。

你可以做

return cmp(self.name, other.name) 

在你的代碼正確的結果

+0

謝謝!原來我的意思是'__eq__'! – monojohnny 2010-01-27 12:42:07

0

查找爲__cmp__的文檔,你就是應該返回一個整數:

應該返回一個負整數,如果 自我<等,零,如果自其他==,一個 正整數,如果自我>等。

4

你很困惑__cmp____eq__

From the documentation of __cmp__:

應該返回一個負整數,如果自我<等,零,如果自其他==,一個正整數,如果自我>等。

__eq__返回一個布爾值,它確定是否兩個對象相等,__cmp__返回其確定兩個對象比彼此更大或更小的整數,所以被稱爲除非有特定__eq____ne____le____ge____lt____gt__方法。

對於您的情況,您確實需要__cmp__方法而不是__eq__,因爲這樣可以節省您爲其他比較實施其他5種方法。

您可以使用cmp() function,並在您__cmp__方法如下:

return cmp(self.name,other.name) 

注意,as highlighted by Ignacio是這個isn't the preferred method in Python 3.0,但在Python 2.x的__cmp__是要走的路。

相關問題