Python如何知道一个对象有一个特定的属性?
1
  • openoker 回复

    比如:

    >>> a = SomeClass()
    >>> a.someProperty = value
    >>> a.property
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: SomeClass instance has no attribute 'property'
    

    怎样在使用之前知道a是否有property这个属性?


    试试hasattr():

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

    在大多数实际情况下,如果一个属性有很大可能存在,那么就直接调用它或者让它引发异常,或者用try/except捕获。这种方法比hasattr快。如果这个属性很多情况下不在,或者你不确定,那么用hasattr将会比触法异常更快。

公告

AI千集是一个专注于写作服务的智能平台
在这里您可以获得本平台自训练的
写作智能体
和小伙伴一起玩转AI,做自己的AI写作机器人
来AI千集,赋能智慧快人一步
扫一扫,快速获取解决方案与报价
立即咨询

积分排行