这是运行后,刚刚从笔记(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