Why does `getattr` not support consecutive attribute retrievals?

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

    You can't put a period in the getattr function because getattr is like accessing the dictionary lookup of the object (but is a little bit more complex than that, due to subclassing and other Python implementation details).

    If you use the 'dir' function on a, you'll see the dictionary keys that correspond to your object's attributes. In this case, the string "b.c" isn't in the set of dictionary keys.

    The only way to do this with getattr is to nest calls:

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

    Luckily, the standard library has a better solution!

    import operator
    operator.attrgetter("b.c")(a)
    

提交回复
热议问题