我想创建一个能够在访问时用任意对象替换自身的对象;如下所示:
class stand_in_object(object):
def __init__(self,obj_ref):
self.obj_ref
def __getattr__(self,key):
pass
#somehow make calling reference now refer to self.obj_ref
#Consider: setattr(ref,name,self.obj_ref) - how do I get ref,name?
#Or perhaps something that replaces the object located at "location"
#so that all references id(self) are "pointing" to
#a new object. Maybe ctypes.memmove?
#------------------------Example use----------------------
class x(object):
def __init__(self):
self.y=stand_in_object(int(5))
a=x()
print a.x.f #calls a.x.__getattr__('f') which sets a.x = int(5)
我以为我可以尝试memmove,或者替换所有引用方法,发现这篇文章:https://benkurtovic.com/2015/01/28/python-object-replacement.html
我正在尝试使用cPickle制作OODB。我希望有一些尚未加载的持久对象,在访问它们之前由一个替代对象引用。如下所示:
loaded = {}
class stand_in(object):
def __init__(self,id,src):
self.id,self.src = id,src
def __getattr__(self,key):
loaded[self.id] = cust_unpickle(self.src)
#Some function to replace reference of standin_obj with loaded object
def persistent_load(id):
if id in loaded: return loaded[id]
else: return stand_in(id,src)
#--------------------------Example-------------------------------
#consider database stores objects a and c, and a.c = c.
a = unpickle(a.id,src) #loaded = {a.id:a}, a.c = stand_in(c.id,c.src)
print a.c.x #calls a.c.__gettattr__ which has the effect:
#c = unpickle(c.id,src)
#and loads = {a.id:a,c.id:c}