2016-11-20 121 views
0

這是運行後,剛剛從筆記(Python對象基礎)的一個例子條件語句的Python

class Cow(): 

    noise = 'moo!' 

    def __init__(self, color): 
    self.color = color 
    print "This cow is " + self.color 

    def make_noise(self): 
    print self.noise 

    def set_color(self, new_color): 
    self.color = new_color 

    def get_color(self): 
    return self.color 

    def __cmp__(self, other): 
    if self.color == other.color: 
     return True 
    else: 
     return False 

    def __str__(self): 
    return self.color + ' ' + self._noise 

blue_cow = Cow('blue') 
red_cow = Cow('red') 

blue_cow.make_noise() 

print red_cow == blue_cow 

blue_cow.set_color('red') 
print red_cow == blue_cow 

此輸出:

moo! 
True 
False 

什麼我不明白就是爲什麼(3號線從最後)

print red_cow == blue_cow 

,而它的假設給假(我認爲),因爲red_cow有紅色和blue_cow有藍色的是給真顏色

最後一行兩行

blue_cow.set_color('red') 
print red_cow == blue_cow 

最後一行爲什麼它執行爲False,而在我看來,我希望它執行爲True

+0

嘗試使用'__eq__'而不是'__cmp__'。 – Fejs

回答

0

要使用__eq__,或者您可以更改方法,以便使用cmp()實際比較字符串。

def __cmp__(self, other): 
    return cmp(self.color, other.color) 

這允許所有其他比較操作工作。

print red_cow == blue_cow # False 
print blue_cow < red_cow # True 
print sorted([red_cow, blue_cow]) # [blue moo!, red moo!] 

blue_cow.color = 'red' 
print red_cow == blue_cow # True 
1

您使用__cmp__,請嘗試使用__eq__它會工作(測試)。

0

https://docs.python.org/2/reference/datamodel.html#object.cmp

由比較操作調用如果富比較(參見上文)是沒有定義 。 應該返回一個負整數如果自<其他,如果 自我=其它,一個正整數如果自我>其他。如果沒有CMP(), EQ()或NE()定義操作,

如果更改__cmp__如果等於返回0,非零如果不相等,也將工作。 On python 2.7.X