Python Language Class Boolean Value


Example

Python 2.x2.7

In Python 2, if you want to define a class boolean value by yourself, you need to implement the __nonzero__ method on your class. The value is True by default.

class MyClass:
    def __nonzero__(self):
        return False

my_instance = MyClass()
print bool(MyClass)       # True
print bool(my_instance)   # False
Python 3.x3.0

In Python 3, __bool__ is used instead of __nonzero__

class MyClass:
    def __bool__(self):
        return False

my_instance = MyClass()
print(bool(MyClass))       # True
print(bool(my_instance))   # False