문제

이 질문은 이미 여기에 답이 있습니다.

내가 원하는 것은 bool (myInstance)이 거짓을 반환하는 것입니다 (그리고/또는/and와 같은 조건부에서 myInstance가 거짓으로 평가하는 것입니다.>, <, =)

나는 이것을 시도했다 :

class test:
    def __bool__(self):
        return False

myInst = test()
print bool(myInst) #prints "True"
print myInst.__bool__() #prints "False"

제안이 있습니까?

(나는 Python 2.6을 사용하고 있습니다)

도움이 되었습니까?

해결책

이 Python 2.x 또는 Python 3.x입니까? Python 2.x의 경우 재정의를 원합니다 __nonzero__ 대신에.

class test:
    def __nonzero__(self):
        return False

다른 팁

코드를 Python3과 호환하려면 다음과 같은 작업을 수행 할 수 있습니다.

class test:
    def __bool__(self):
        return False
    __nonzero__=__bool__

당신의 경우 test 클래스는 목록과 같으며 정의합니다 __len__ 그리고 bool(myInstanceOfTest) 돌아올 것입니다 True 1 개 이상의 항목이있는 경우 (비어 있지 않은 목록) False 항목이 0 인 경우 (빈 목록). 이것은 나를 위해 효과가있었습니다.

class MinPriorityQueue(object):
    def __init__(self, iterable):
        self.priorityQueue = heapq.heapify(iterable)
    def __len__(self):
        return len(self.priorityQueue)

>>> bool(MinPriorityQueue([])
False
>>> bool(MinPriorityQueue([1,3,2])
True

John La Rooy와 유사하게 사용합니다.

class Test(object):
    def __bool__(self):
        return False

    def __nonzero__(self):
        return self.__bool__()

이것은 @John-La-Rooy의 답변에 대한 의견이지만 아직 언급 할 수는 없습니다 :)

Python3 호환성을 위해 할 수 있습니다 (나는 이것을 찾고 있었다)

class test(object):
    def __bool__(self):
        return False

    __nonzero__=__bool__

유일한 문제는 반복해야한다는 것입니다 __nonzero__ = __bool__ 변경할 때마다 __bool__ 서브 클래스. 그렇지 않으면 __nonzero__ 슈퍼 클래스에서 보관됩니다. 당신은 시도 할 수 있습니다

from builtins import object  # needs to be installed !

class test(object):
    def __bool__(self):
        return False

    __nonzero__=__bool__

작동하지 않거나 메타 클라스를 작성해야합니다. :) 자신.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top