Why does `getattr` not support consecutive attribute retrievals?

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

    You can call the multiple getattr without calling a function within function by splitting the dot operators and performing a getattr() for each dot operator

    def multi_getattr(self,obj, attr, default = None):
              attributes = attr.split(".")
              for i in attributes:
                  try:
                      obj = getattr(obj, i)
                  except AttributeError:
                      if default:
                          return default
                      else:
                          raise
              return obj
    

    If suppose you wish to call a.b.c.d you can do it via a.multi_getattr('b.c.d'). This will generalise the operation without worrying about the count of dot operation one has in the string.

提交回复
热议问题