Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overload Python's __bool__ method? [duplicate]

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 >>> 
like image 881
dividebyzero Avatar asked Jan 18 '12 12:01

dividebyzero


People also ask

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.

How do you overload in Python?

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

How do you overload an assignment operator in Python?

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.

What is Python magic method?

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.


1 Answers

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

like image 99
Sven Marnach Avatar answered Sep 28 '22 01:09

Sven Marnach