Why does `getattr` not support consecutive attribute retrievals?

后端 未结 7 1251
梦如初夏
梦如初夏 2021-02-01 01:53
class A(): pass

a = A()
b = A()

a.b = b
b.c = 1

a.b     # this is b
getattr(a, \"b\") # so is this

a.b.c   # this is 1   
getattr(a, \"b.c\") # this raises an Attrib         


        
7条回答
  •  臣服心动
    2021-02-01 02:18

    I think the most straight forward way to achieve what you want is to use operator.attrgetter.

    >>> import operator
    >>> class B():
    ...   c = 'foo'
    ... 
    >>> class A():
    ...   b = B()
    ... 
    >>> a = A()
    >>> operator.attrgetter('b.c')(a)
    'foo'
    

    If the attribute doesn't exist then you'll get an AttributeError

    >>> operator.attrgetter('b.d')(a)
    Traceback (most recent call last):
      File "", line 1, in 
    AttributeError: B instance has no attribute 'd'
    

提交回复
热议问题