나는 마법 비교 메소드의 혼란스러운 행동을 경험했다. 클래스는 일반 INT 또는 플로트에 MutNum 개체를 비교, 어떻게해야 무엇합니까파이썬 매직 메소드 혼동
class MutNum(object):
def __init__ (self, val):
self.val = val
def setVal(self, newval):
self.val = newval
def __str__(self):
return str(self.val)
def __repr__(self):
return str(self.val)
# methods for comparison with a regular int or float:
def __eq__(self, other):
return self.val == other
def __gt__(self, other):
return self.val > other
def __lt__(self, other):
return self.val < other
def __ge__(self, other):
return self.__gt__(other) or self.__eq__(other)
def __le__(self, other):
return self.__lt__(other) or self.__eq__(other)
아무 문제가 없습니다 : 우리는 다음과 같은 클래스가 있다고 가정하자. 그러나 이것이 내가 이해하지 못하는 것입니다. 마법 메서드에 두 개의 MutNum 개체가 주어지면 잘 비교됩니다.
왜이 기능이 작동합니까? 감사. (A repr
-like 표기법을 사용하는 대신 변수 참조) 다음과 같이
예를 들어,'__add__'와'__radd__ '와 같은 관계에있는'__gt__'과'__lt__'를 생각하면 도움이 될 것입니다. 첫 번째가 적용되지 않으면, 파이썬은 다른 피연산자를 반대로 시도합니다. – chepner