为自定义类重载bool()
我想要的是,当我用 bool(myInstance) 的时候,它能返回 False(而且在像 if、or、and 这样的条件判断中,myInstance 也能被当作 False 来处理)。我知道怎么重写大于、小于和等于这些比较运算符。
我试过这个:
class test:
def __bool__(self):
return False
myInst = test()
print bool(myInst) #prints "True"
print myInst.__bool__() #prints "False"
有什么建议吗?
(我正在使用 Python 2.6)
6 个回答
10
如果你的 test
类像列表一样,那么你需要定义一个叫 __len__
的方法。这样,当你用 bool(myInstanceOfTest)
来检查这个类的实例时,如果里面有一个或更多的东西(也就是非空列表),它会返回 True
;如果里面什么都没有(空列表),它会返回 False
。这个方法对我来说是有效的。
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
70
如果你想让你的代码在未来能够和Python 3兼容,可以试试这样做:
class test:
def __bool__(self):
return False
__nonzero__=__bool__
72
这是在问你用的是Python 2.x还是Python 3.x?如果你用的是Python 2.x,那你需要重写__nonzero__
这个方法。
class test:
def __nonzero__(self):
return False