Boolean value of objects in Python

前端 未结 2 789
花落未央
花落未央 2020-11-29 08:13

As we know, Python has boolean values for objects: If a class has a __len__ method, every instance of it for which __len__() happens to return 0 wi

相关标签:
2条回答
  • 2020-11-29 08:34

    Refer to the Python docs for __nonzero__.

    class foo(object):
        def __nonzero__( self) :
            return self.bar % 2 == 0
    
    def a(foo):
        if foo:
            print "spam"
        else:
            print "eggs"
    
    def main():
        myfoo = foo()
        myfoo.bar = 3
        a(myfoo)
    
    if __name__ == "__main__":
        main()
    
    0 讨论(0)
  • 2020-11-29 08:35

    In Python < 3.0 :

    You have to use __nonzero__ to achieve what you want. It's a method that is called automatically by Python when evaluating an object in a boolean context. It must return a boolean that will be used as the value to evaluate.

    E.G :

    class Foo(object):
    
        def __init__(self, bar) :
            self.bar = bar
    
        def __nonzero__(self) :
            return self.bar % 2 == 0
    
    if __name__ == "__main__":
         if (Foo(2)) : print "yess !"
    

    In Python => 3.0 :

    Same thing, except the method has been renamed to the much more obvious __bool__.

    0 讨论(0)
提交回复
热议问题