Boolean value of objects in Python

Python 2.x

Use the __nonzero__ magic method. It’s 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 !"

Python 3.x

Use __bool__ instead, in the same way.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)