How to add property to a class dynamically?

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

    Only way to dynamically attach a property is to create a new class and its instance with your new property.

    class Holder: p = property(lambda x: vs[i], self.fn_readonly)
    setattr(self, k, Holder().p)
    

提交回复
热议问题