Python hasattr vs getattr

后端 未结 2 1077
予麋鹿
予麋鹿 2020-12-31 09:48

I have been reading lately some tweets and the python documentation about hasattr and it says:

hasattr(object, name)

The

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-31 10:01

    Seems that hasattr has a problem with swallowing exceptions (at least in Python 2.7), so probably is better to stay away from it until it's fixed.

    Take, for instance, the following code:

    >>> class Foo(object):
    ...     @property
    ...     def my_attr(self):
    ...         raise ValueError('nope, nope, nope')
    ...
    >>> bar = Foo()
    >>> bar.my_attr
    Traceback (most recent call last):
      File "", line 1, in 
      File "", line 4, in my_attr
    ValueError: nope, nope, nope
    >>> hasattr(Foo, 'my_attr')
    True
    >>> hasattr(bar, 'my_attr')
    False
    >>> getattr(bar, 'my_attr', None)
    Traceback (most recent call last):
      File "", line 1, in 
      File "", line 4, in my_attr
    ValueError: nope, nope, nope
    >>>
    

提交回复
热议问题