How to add property to a class dynamically?

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

    Not sure if I completely understand the question, but you can modify instance properties at runtime with the built-in __dict__ of your class:

    class C(object):
        def __init__(self, ks, vs):
            self.__dict__ = dict(zip(ks, vs))
    
    
    if __name__ == "__main__":
        ks = ['ab', 'cd']
        vs = [12, 34]
        c = C(ks, vs)
        print(c.ab) # 12
    

提交回复
热议问题