Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding 'to boolean' operator in python?

Tags:

python

I'm using a class that is inherited from list as a data structure:

class CItem( list ) :   pass oItem = CItem() oItem.m_something = 10 oItem += [ 1, 2, 3 ] 

All is perfect, but if I use my object of my class inside of an 'if', python evaluates it to False if underlying the list has no elements. Since my class is not just list, I really want it to evaluate False only if it's None, and evaluate to True otherwise:

a = None if a :   print "this is not called, as expected" a = CItem() if a :   print "and this is not called too, since CItem is empty list. How to fix it?" 
like image 640
grigoryvp Avatar asked Apr 17 '09 18:04

grigoryvp


People also ask

How do boolean operators work in Python?

While and as well as or operator needs two operands, which may evaluate to true or false, not operator needs one operand evaluating to true or false. Boolean and operator returns true if both operands return true. The not operator returns true if its operand is a false expression and returns false if it is true.

Can I overload and operator in Python?

Python does not limit operator overloading to arithmetic operators only. We can overload comparison operators as well.

What are the 3 Boolean operators in Python?

There are three logical operators that are used to compare values. They evaluate expressions down to Boolean values, returning either True or False . These operators are and , or , and not and are defined in the table below.


1 Answers

In 2.x: override __nonzero__(). In 3.x, override __bool__().

like image 109
John Millikin Avatar answered Oct 07 '22 03:10

John Millikin