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
- 但由于我试图比较字符串,这不正确。
我在这里做错了什么?
Thankyou - 你会得到蜱虫(尽管其他人提供了类似的信息),因为这是最清楚的解释! – monojohnny 2010-01-27 12:41:23
正如其他人所评论的,__cmp __()已过时。定义__lt __(),__eq __()和__gt __()来代替。按照http://docs.python.org/dev/whatsnew/3.0.html#ordering-comparisons – smci 2011-06-30 03:51:31