tags:

views:

636

answers:

2

As we know, Python has boolean values for objects: If a class has a length attribute, every instance of it which happens to have length 0 will be evaluated as a boolean False (for example, the empty list).

In fact, every iterable, empty custom object is evaluated as False if it appears in boolean expression.

Now suppose I have a class foo with attribute bar. How can I define its truth value, so that, say, it will be evaluated to True if bar % 2 == 0 and False otherwise?

For example:

myfoo = foo()
myfoo.bar = 3
def a(myfoo):
    if foo:
        print "spam"
    else:
        print "eggs"

so, a(myfoo) should print "eggs".

Thanks!

+10  A: 
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()

refer to this

sunqiang
Excellent, trivial, Pythonic! Thank you :)
ooboo
You are welcome :)
sunqiang
+6  A: 

In Python < 3.0 :

You can 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 in the much more obvious __bool__.

e-satis