Possible Duplicate:
defining “boolness” of a class in python
I thought this should print "False", why is it printing "True"?
>>> class Foo(object): ... def __bool__(self): ... return False ... >>> f = Foo() >>> if f: ... print "True" ... else: ... print "False" ... True >>>
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.
In Python, overloading is achieved by overriding the method which is specifically for that operator, in the user-defined class. For example, __add__(self, x) is a method reserved for overloading + operator, and __eq__(self, x) is for overloading == .
To perform operator overloading, Python provides some special function or magic function that is automatically invoked when it is associated with that particular operator. For example, when we use + operator, the magic method __add__ is automatically invoked in which the operation for + operator is defined.
Magic methods in Python are the special methods that start and end with the double underscores. They are also called dunder methods. Magic methods are not meant to be invoked directly by you, but the invocation happens internally from the class on a certain action.
You should define __nonzero__()
in Python 2.x. It was only renamed to __bool__()
in Python 3.x. (The name __nonzero__()
actually predates the introduction of the bool
type by many years.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With