2016-06-20 2 views
0

나는 단순한 Old Maid 게임을 만들고 있습니다. 다음은 플레이어의 손에 내 클래스입니다 :왜 비교가 int를 반환하지 않았습니까

class OldMaidHand(Hand): 
    def removeMatches(self): 
     count=0; 
     originalCards=self.cards[:]; 
     for card in originalCards: 
      match=Card(3-card.suit,card.rank); 
      if match in self.cards: 
       self.cards.remove(card); 
       self.cards.remove(match); 
       print "Hand %s: %s matches %s "%(self.name,card,match); 
       count=count+1; 
      return count;` 

는하지만 다음과 같은 오류를 보여주는 것 :

TypeError :comparison did not return an int.

여기 Card 클래스 내 __cmp__() 방법이다. documentation for __cmp__에서

def __cmp__(self,other): 
     if self.suit>other.suit: 
      return 1 
     if self.suit<other.suit: 
      return -1 
     if self.rank>other.rank: 
      return 1 
     if self.rank<other.rank: 
      return -1 
+0

수업의 형식을 수정하십시오. – Carcigenicate

+4

만약 그들이 동등하다면? – jonrsharpe

+3

'if' 절이 True가 아닌 경우'__cmp__'는'None'을 반환합니다. 이것은 괜찮지 않습니다. –

답변

1

: 즉

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 조건이 하나도 없으면 __cmp__은 명시 적으로 다른 것을 반환하지 않는 파이썬 함수의 기본값 인 None을 반환하는 함수의 "끝에서 제외됩니다". 이것은 오류의 원인입니다 (None은 정수가 아니기 때문에).

나는 당신의 코드를 너무 조심스럽게 검사하지는 않았지만, 당신은 계급과 슈트가 동등한 경우를 소홀히 한 것처럼 보입니다. 아마도 안전 장치로, 기능이 끝나면 단순히 return 0을해야합니다. 조건이 충족되지 않았지만 카드가 동일하지 않은 경우를 발견하지 않는 한.

+0

__cmp__ method에 대한 반환 값을 놓쳤습니다. 반환 값 0을 추가 한 후 제대로 작동합니다. – user3973383

관련 문제