How to add property to a class dynamically?

前端 未结 24 1924
梦毁少年i
梦毁少年i 2020-11-22 12:44

The goal is to create a mock class which behaves like a db resultset.

So for example, if a database query returns, using a dict expression, {\'ab\':100, \'cd\'

24条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 13:13

    class atdict(dict):
      def __init__(self, value, **kwargs):
        super().__init__(**kwargs)
        self.__dict = value
    
      def __getattr__(self, name):
        for key in self.__dict:
          if type(self.__dict[key]) is list:
            for idx, item in enumerate(self.__dict[key]):
              if type(item) is dict:
                self.__dict[key][idx] = atdict(item)
          if type(self.__dict[key]) is dict:
            self.__dict[key] = atdict(self.__dict[key])
        return self.__dict[name]
    
    
    
    d1 = atdict({'a' : {'b': [{'c': 1}, 2]}})
    
    print(d1.a.b[0].c)
    

    And the output is:

    >> 1
    

提交回复
热议问题