lundi 28 septembre 2015

Check if object attributes are non-empty python

I can check if python list or dictionary are empty or not like this

lis1, dict1 = [], {}
# similar thing can be done for dict1
if lis1:
    # Do stuff
else:
    print "List is empty"

But if I try to do this with my class object, i.e checking if my object attributes are non-empty by typing if my_object: this always evaluate to True

>>> class my_class(object):
...   def __init__(self):
...     self.lis1 = []
...     self.dict1 = {}
... 
>>> obj1 = my_class()
>>> obj1
<__main__.my_class object at 0x10c793250>
>>> if obj1:
...   print "yes"
... 
yes

I can write a function specifically to check if my object attributes are non-empty and then call if obj1.is_attributes_empty():, but I am more interested in knowing how if evaluates the standard data-types like list and dict to True or False depending on the items they contain or are empty.

If I want to achieve this functionality with my class object what methods I need to override or make changes to

Aucun commentaire:

Enregistrer un commentaire