Why does `getattr` not support consecutive attribute retrievals?

后端 未结 7 1235
梦如初夏
梦如初夏 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:41

    Because getattr doesn't work that way. getattr gets attribute of a given object (first argument) with a given name (second argument). So your code:

    getattr(a, "b.c") # this raises an AttributeError
    

    means: Access "b.c" attribute of object referenced by "a". Obviously your object doesn't have attribute called "b.c".

    To get "c" attribute you must use two getattr calls:

    getattr(getattr(a, "b"), "c")
    

    Let's unwrap it for better understanding:

    b = getattr(a, "b")
    c = getattr(b, "c")
    
    0 讨论(0)
提交回复
热议问题