Class Boolean Value

suggest change

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

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents