条件语句 Python

Conditional Statement 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

给出 True 而它应该给出 False(我的观点)因为 red_cow 有红色而 blue_cow 有蓝色

最后一行两行

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

最后一行为什么它执行为 False 而我认为我希望它执行为 True

您正在使用 __cmp__,请尝试使用 __eq__,它会起作用(已测试)。

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

Called by comparison operations if rich comparison (see above) is not defined. Should return a negative integer if self < other, zero if self =other, a positive integer if self > other. If no cmp(), eq() or ne() operation is defined,

如果您将 __cmp__ 更改为 return 如果相等则为 0,如果不相等则为非零,它也将起作用。在 python 2.7.X

您想使用 __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