判断 Python 对象是否包含某个属性的方法

先创建两个类,判断类的属性是否存在:
 

class Foo(object):
    def __init__(self):
        super(Foo, self).__init__()
        self.is_whole = 1


class Doo(object):
    def __init__(self):
        super(Doo, self).__init__()

f = Foo()
d = Doo()



方法一:通过异常捕捉来实现逻辑
 

try:
    print(f.is_whole)
except AttributeError as e:
    pass

try:
    print(d.is_whole)
except AttributeError as e:
    print('d无这个属性')

方法二:调用hasattr方法: hasattr(object, name)

# 说明:判断对象object是否包含名为name的特性(hasattr是通过调用getattr(ojbect, name)是否抛出异常来实现的)。
# 参数object:对象。
# 参数name:特性名称。
 

>>> hasattr(f, 'is_whole')

True

>>> hasattr(d, 'is_whole')

False

方法三:使用dir方法

obj = dir(f)
if 'is_whole' in obj:
    print(f.is_whole)
else:
    print('f无这个属性')


obj = dir(d)
if 'is_whole' in obj:
    print(d.is_whole)
else:
    print('d无这个属性')
发布了374 篇原创文章 · 获赞 526 · 访问量 71万+

猜你喜欢

转载自blog.csdn.net/xun527/article/details/88059666
今日推荐