How to add property to a class dynamically?

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

    The best way to achieve is by defining __slots__. That way your instances can't have new attributes.

    ks = ['ab', 'cd']
    vs = [12, 34]
    
    class C(dict):
        __slots__ = []
        def __init__(self, ks, vs): self.update(zip(ks, vs))
        def __getattr__(self, key): return self[key]
    
    if __name__ == "__main__":
        c = C(ks, vs)
        print c.ab
    

    That prints 12

        c.ab = 33
    

    That gives: AttributeError: 'C' object has no attribute 'ab'

提交回复
热议问题