为了账号安全,请及时绑定邮箱和手机立即绑定

如何知道对象在Python中是否具有属性

如何知道对象在Python中是否具有属性

呼如林 2019-07-22 15:12:04
如何知道对象在Python中是否具有属性Python中是否有确定对象是否具有某种属性的方法?例如:>>> a = SomeClass()>>> a.someProperty = value>>> a.propertyTraceback (most recent call last):   File "<stdin>", line 1, in <module>AttributeError: SomeClass instance has no attribute 'property'你怎么知道a有属性property在使用之前?
查看完整描述

3 回答

?
手掌心

TA贡献1942条经验 获得超3个赞

试一试hasattr():

if hasattr(a, 'property'):
    a.property

Zweiterlinde的答案下面,他提供了关于请求宽恕的好建议!一种非常仿生的方法!

python中的一般做法是,如果属性可能大部分时间都在那里,那么只需调用它,让异常传播,或者使用TRY/EXT块来捕获它。这可能比hasattr..如果属性可能大部分时间不在那里,或者您不确定,则使用hasattr可能比反复陷入异常块更快。



查看完整回答
反对 回复 2019-07-23
  • 3 回答
  • 0 关注
  • 286 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信