在Python中分配类布尔值 [英] Assign class boolean value in Python
问题描述
如果Python中的语句允许您执行以下操作:
If statements in Python allow you to do something like:
if not x:
print "X is false."
如果你使用空列表,空字典,None,但是如果你有自己的自定义类怎么办?
This works if you're using an empty list, an empty dictionary, None, 0, etc, but what if you have your own custom class? Can you assign a false value for that class so that in the same style of conditional, it will return false?
推荐答案
您需要使用这个方法,在您的网站上实施 __ nonzero __
方法类。这应该返回True或False以确定真值:
You need to implement the __nonzero__
method on your class. This should return True or False to determine the truth value:
class MyClass(object):
def __init__(self, val):
self.val = val
def __nonzero__(self):
return self.val != 0 #This is an example, you can use any condition
x = MyClass(0)
if not x:
print 'x is false'
如果未定义 __ nonzero __
,则实现将调用 __ len __
,实例将被视为True如果它返回一个非零值。如果 __ len __
未定义,所有实例将被视为True。
If __nonzero__
has not been defined, the implementation will call __len__
and the instance will be considered True if it returned a nonzero value. If __len__
hasn't been defined either, all instances will be considered True.
在Python 3中, __ bool __
而不是 __ nonzero __
。
In Python 3, __bool__
is used instead of __nonzero__
.
这篇关于在Python中分配类布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!