覆盖自定义类的bool()

Pon*_*dle 50 python casting boolean class python-2.x

所有我想要的是bool(myInstance)返回False(并且myInstance在条件中评估为False,如if /或/和.我知道如何覆盖>,<,=)

我试过这个:

class test:
    def __bool__(self):
        return False

myInst = test()
print bool(myInst) #prints "True"
print myInst.__bool__() #prints "False"
Run Code Online (Sandbox Code Playgroud)

有什么建议?

(我使用的是Python 2.6)

Joe*_*way 67

这是Python 2.x还是Python 3.x?对于Python 2.x,您希望覆盖它__nonzero__.

class test:
    def __nonzero__(self):
        return False
Run Code Online (Sandbox Code Playgroud)


Joh*_*ooy 60

如果你想让代码向前兼容python3,你可以做这样的事情

class test:
    def __bool__(self):
        return False
    __nonzero__=__bool__
Run Code Online (Sandbox Code Playgroud)


Ice*_*dor 9

如果你的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
Run Code Online (Sandbox Code Playgroud)

  • 这很方便。感谢您提供这个替代解决方案。 (2认同)

tkn*_*man 5

类似于 John La Rooy,我使用:

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

    def __nonzero__(self):
        return self.__bool__()
Run Code Online (Sandbox Code Playgroud)