How to add property to a class dynamically?

前端 未结 24 2219
梦毁少年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:33

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

    So what you want is a dictionary where you can spell a['b'] as a.b?

    That's easy:

    class atdict(dict):
        __getattr__= dict.__getitem__
        __setattr__= dict.__setitem__
        __delattr__= dict.__delitem__
    

提交回复
热议问题