__cmp__ method is this not working as expected in Python 2.x?
-
23-09-2019 - |
문제
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)
The output here is:
cmp method called with self=hello,other=there
True
False
Which is not what I expected: I'm trying to say 'two instances are equal if the name fields are equal'.
If I simply return False
from the __cmp__
function, this reports as True
as well!!
If I return -1
, then I get False
- but since I'm trying to compare strings, this doesn't feel right.
What am I doing wrong here?
해결책
__cmp__(x,y)
should return a negative number (e.g. -1) if x < y
, a positive number (e.g. 1) if x > y
and 0 if x == y
. You should never return a boolean with it.
What you're overloading is __eq__(x, y)
.
다른 팁
the __cmp__
method should return -1, 0 or 1, when self < other, self == other, self > other respectvelly.
You can do
return cmp(self.name, other.name)
in your code for a proper result
You're confusing __cmp__
with __eq__
.
From the documentation of __cmp__
:
Should return a negative integer if self < other, zero if self == other, a positive integer if self > other.
__eq__
returns a boolean which determines if two objects are equal, __cmp__
returns an integer which determines if the two objects are greater or less than each other, and so is called unless you have specific __eq__
, __ne__
, __le__
, __ge__
, __lt__
and __gt__
methods.
In your case you do want a __cmp__
method rather than __eq__
as it will save you implementing the other 5 methods for the other comparisons.
You could use the cmp()
function and put the following in your __cmp__
method:
return cmp(self.name,other.name)
Note, as highlighted by Ignacio is this isn't the preferred method in Python 3.0, but in Python 2.x __cmp__
is the way to go.
Microsoft는 이제 사이트 내용에서보기에서 Micropeed를 비활성화했으며 동작에서 '목록 항목의 이벤트 대기
해결 방법
공개 SharePoint Designer
모든 파일> 목록> 게시 된 피드> 속성> 설정 아래에서 브라우저에서 숨기기를 눌러 저장합니다.
은 워크 플로로 돌아가서 동작하에 '목록 항목의 이벤트 대기'를 선택하고 마이크로 피로 듀드는 이제 목록에서 다시 실행할 수 있어야합니다.
Lookup the documentation for __cmp__
, youre supposed to return an integer:
Should return a negative integer if self < other, zero if self == other, a positive integer if self > other.