I wanted, to make traversable (by DB, single file or just as string) class in python. I Write this (shorted):
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)
And yea – that work, but… When i’m making more instances, all of them are like singleton.
So – how to set attribute to instance without _setattr_?
PS. I got idea – make in set/getattr an pass for keys/vals, but it’ll make mess.
your
__separator__,__keys__,__vals__and__slots__are attributes of the object “Storage”(class object). I don’t know if it’s exactly the same, but I’d call it static variables of the class.If you want to have different values for each instance of Storage, define each of these variables in your
__init__function:edited so getattr and setattr works
I got that problem 2 days ago. Don’t know if that’s exactly your problem, but you said that about “its like I have a singleton”