Assign class boolean value in Python

ぃ、小莉子 提交于 2019-11-29 09:23:08

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'

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.

In Python 3, __bool__ is used instead of __nonzero__.

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

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

Or, if you want to be ultra-portable, you can define __len__ only, which will have the same effect in both languages, but that has the (potential) downside that it implies that your object has a meaningful measure of length (which it may not).

This will work for any instance, depending on the actual logic you put in the method.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!