Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean value of objects in Python

Tags:

python

boolean

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 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(foo):     if foo:         print "spam"     else:         print "eggs" 

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

like image 662
ooboo Avatar asked Jul 06 '09 13:07

ooboo


People also ask

How do you find the Boolean value in Python?

bool() in Python. Python bool() function is used to return or convert a value to a Boolean value i.e., True or False, using the standard truth testing procedure.

What are boolean values in Python?

There are two Boolean. values: True and False. Values in Python can be compared using comparison operations, and Boolean logic can be formulated with the use of logic operations.

What are boolean objects?

The Boolean object represents two values, either "true" or "false". If value parameter is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false.

What is __ bool __ in Python?

The __bool__ method must return a boolean value, True or False . In this example, the __bool__ method returns False if the age is less than 18 or greater than 65. Otherwise, it returns True . The person object has the age value of 16 therefore it returns False in this case.


2 Answers

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__.

like image 198
e-satis Avatar answered Sep 22 '22 18:09

e-satis


In Python 2, use __nonzero__:

Refer to the Python 2 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() 
like image 24
sunqiang Avatar answered Sep 23 '22 18:09

sunqiang