在Python中分配类布尔值

问题描述 投票:0回答:2

Python 中的 If 语句允许您执行以下操作:

   if not x:
       print "X is false."

如果您使用空列表、空字典、None、0 等,这可以工作,但是如果您有自己的自定义类怎么办?您能否为该类分配一个 false 值,以便在相同的条件样式中,它将返回 false?

python class conditional-statements
2个回答
40
投票

从 Python 3 开始,您需要在类上实现

__bool__
方法。这应该返回 True 或 False 以确定真值:

class MyClass:
    def __init__(self, val):
        self.val = val
    def __bool__(self):
        return self.val != 0  #This is an example, you can use any condition

x = MyClass(0)
if not x:
    print 'x is false'

如果尚未定义

__bool__
,则实现将调用
__len__
,并且如果实例返回非零值,则该实例将被视为 True。如果
__len__
也未定义,则所有实例都将被视为 True。

进一步阅读:


在Python 2中,使用特殊方法

__nonzero__
代替了
__bool__


10
投票
class Foo:
     def __nonzero__(self): return False
     __bool__ = __nonzero__ # this is for python3

In [254]: if Foo():
   .....:     print 'Yeah'
   .....: else: print 'Nay'
   .....:
Nay

或者,如果您想要超便携,您可以仅定义

__len__
,这在两种语言中具有相同的效果,但这有一个(潜在的)缺点,即它意味着您的对象具有有意义的长度度量(也可能不是)。

这适用于任何实例,具体取决于您在方法中放入的实际逻辑。

© www.soinside.com 2019 - 2024. All rights reserved.