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?"
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.
Python does not limit operator overloading to arithmetic operators only. We can overload comparison operators as well.
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.
In 2.x: override __nonzero__()
. In 3.x, override __bool__()
.
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