Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign class boolean value in Python

Tags:

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, an empty dictionary, None, 0, etc, but what if you have your own custom class? Can you assign a false value for that class so that in the same style of conditional, it will return false?

like image 205
Kelketek Avatar asked Mar 20 '12 13:03

Kelketek


People also ask

How do you assign a boolean value in Python?

If you want to define a boolean in Python, you can simply assign a True or False value or even an expression that ultimately evaluates to one of these values. You can check the type of the variable by using the built-in type function in Python.

Is boolean a class Python?

Summary. Python uses the bool class to represent boolean values: True and False . True and False are instances of the bool class.

How do you assign a value to a boolean?

To declare a Boolean variable, we use the keyword bool. To initialize or assign a true or false value to a Boolean variable, we use the keywords true and false. Boolean values are not actually stored in Boolean variables as the words “true” or “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

You need to implement the __nonzero__ method on your class. This should return True or False to determine the truth value:

class MyClass(object):     def __init__(self, val):         self.val = val     def __nonzero__(self):         return self.val != 0  #This is an example, you can use any condition  x = MyClass(0) if not x:     print 'x is false' 

If __nonzero__ has not been defined, the implementation will call __len__ and the instance will be considered True if it returned a nonzero value. If __len__ hasn't been defined either, all instances will be considered True.

In Python 3, __bool__ is used instead of __nonzero__.

like image 158
interjay Avatar answered Oct 03 '22 19:10

interjay


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.

like image 25
Marcin Avatar answered Oct 03 '22 20:10

Marcin