class C:
def __init__(self):
self.x = 1
self.y = 2
def regist(self, key, val):
self.__dict__[key] = val
c = C()
print c.__dict__
c.regist("z", 3)
c.regist("func", lambda x: "".join(["=>", str(x), "<="]))
print c.__dict__
print c.x, c.y, c.z, c.func("__dict__")
运行结果:
{'y': 2, 'x': 1}
{'y': 2, 'x': 1, 'z': 3, 'func': <function <lambda> at 0x2b55c97de668>}
1 2 3 =>__dict__<=
结论:python对象内部的字典存储所有的命名空间。
所以有用 self.__dict__.update(pickle.load(f))
把对象存在类实例中。
class Dataset():
def load(self, filename):
with open(filename, 'rb') as f:
self.__dict__.update(pickle.load(f))
来源:http://yjliu.net/blog/2012/04/29/dynamic-member-in-python-class.html