Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, what operator to override for "if object:"?

I find it very handy to check if an object is "empty" with the following construct:

l=[]
if l:
     do_stuff()

For a standard python list, the if will be executed only if the list is not empty.

My question is, how can I implement the same idea for my own objects?

like image 441
static_rtti Avatar asked Mar 13 '11 11:03

static_rtti


People also ask

What does __ add __ do in Python?

__add__ magic method is used to add the attributes of the class instance. For example, let's say object1 is an instance of a class A and object2 is an instance of class B and both of these classes have an attribute called 'a', that holds an integer.

Which function overloads the == operator 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 == .

What the __ repr __ function does?

Python __repr__() function returns the object representation in string format. This method is called when repr() function is invoked on the object. If possible, the string returned should be a valid Python expression that can be used to reconstruct the object again.

Does Python in use __ eq __?

Python automatically calls the __eq__ method of a class when you use the == operator to compare the instances of the class. By default, Python uses the is operator if you don't provide a specific implementation for the __eq__ method.


2 Answers

Define a method __bool__ (Python 3.x) or __nonzero__ (2.x). Or define both for portability, with one returning the result of the other.

like image 143
Fred Foo Avatar answered Oct 05 '22 14:10

Fred Foo


Implement __nonzero__ for Python 2 and __bool__ for Python 3:

class AlwaysTrueObject:
    def __bool__(self):
        return True
    __nonzero__ = __bool__
like image 33
phihag Avatar answered Oct 05 '22 13:10

phihag