Assign class boolean value in Python

后端 未结 2 1039
死守一世寂寞
死守一世寂寞 2020-12-11 01:12

If statements in Python allow you to do something like:

   if not x:
       print \"X is false.\"

This works if you\'re using an empty list

2条回答
  •  没有蜡笔的小新
    2020-12-11 01:21

    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.

提交回复
热议问题