如何动态地向类添加属性?
{'ab':100, 'cd':200}
>>> dummy.ab100
ks = ['ab', 'cd']vs = [12, 34]class C(dict): def __init__(self, ks, vs): for i, k in enumerate(ks): self[k] = vs[i] setattr(self, k, property(lambda x: vs[i], self.fn_readyonly)) def fn_readonly(self, v) raise "It is ready only"if __name__ == "__main__": c = C(ks, vs) print c.ab
c.ab
setattr
k = property(lambda x: vs[i])
__getattribute__
qq_花开花谢_0
相关分类