這是運行後,剛剛從筆記(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
嘗試使用'__eq__'而不是'__cmp__'。 – Fejs