我想在python中制作可遍历的(通过DB、单个文件或只是作为字符串)类。我写这个(短):
from json import JSONDecoder, JSONEncoder
def json_decode(object): return JSONDecoder().decode(object)
def json_encode(object): return JSONEncoder().encode(object)
class Storage:
__separator__ = 'ANY OF ANYS'
__keys__ = []
__vals__ = []
__slots__ = ('__keys__', '__vals__', '__separator__')
def __getattr__(self, key):
try:
return self.__vals__[self.__keys__.index(key)]
except IndexError:
raise AttributeError
def __setattr__(self, key, val):
self.__keys__.append(key)
self.__vals__.append(val)
def store(self):
return (json_encode(self.__keys__) + self.__separator__ +
json_encode(self.__vals__))
def restore(self, stored):
stored = stored.split(self.__separator__)
for (key, val) in zip(json_decode(stored[0]), json_decode(stored[1])):
setattr(self, key, val)
是的 - 那行得通,但是......当我制作更多实例时,它们都像单身。
那么 - 如何在没有 _ setattr _ 的情况下将属性设置为实例?
PS。我有想法 - 在set/getattr中设置keys/vals的通行证,但它会弄得一团糟。