检查对象属性是否为非空python

Anu*_*rma 5 python if-statement

我可以像这样检查python列表或字典是否为空

lis1, dict1 = [], {}
# similar thing can be done for dict1
if lis1:
    # Do stuff
else:
    print "List is empty"
Run Code Online (Sandbox Code Playgroud)

如果我尝试对我的类对象执行此操作,即通过键入if my_object:此始终评估为来检查我的对象属性是否为非空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
Run Code Online (Sandbox Code Playgroud)

我可以专门编写一个函数来检查我的对象属性是否为非空,然后调用if obj1.is_attributes_empty():,但我更想知道如何if评估standard data-typeslikelistdicttoTrueFalse取决于它们包含或为空的项目。

如果我想用我的类对象实现这个功能,我需要覆盖或更改哪些方法?

Joh*_*ooy 7

您需要实现该__nonzero__方法(或__bool__用于 Python3)

https://docs.python.org/2/reference/datamodel.html#object。非零

class my_class(object):
    def __init__(self):
        self.lis1 = []
        self.dict1 = {}

    def __nonzero__(self):
        return bool(self.lis1 or self.dict1)

obj = my_class()
if obj:
    print "Available"
else:
    print "Not available"
Run Code Online (Sandbox Code Playgroud)

Python 还会检查该__len__方法的真实性,但这对您的示例似乎没有意义。

如果你有很多属性要检查,你可能更喜欢

return any((self.lis1, self.dict1, ...))
Run Code Online (Sandbox Code Playgroud)