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?
__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.
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 == .
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.
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.
Define a method __bool__
(Python 3.x) or __nonzero__
(2.x). Or define both for portability, with one returning the result of the other.
Implement __nonzero__
for Python 2 and __bool__
for Python 3:
class AlwaysTrueObject:
def __bool__(self):
return True
__nonzero__ = __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