[英]Traversing a Python object tree
I'm trying to implement dynamic reloading objects in Python, that reflect code changes live. 我正在尝试在Python中实现动态重载对象,以实时反映代码更改。
Modules reloading is working, but I have to recreate every instance of the modules' classes for changes to become effective. 模块重装工作正常,但是我必须重新创建模块类的每个实例,以使更改生效。
The problem is that objects data (objects __dict__
content) is lost during the process. 问题在于在此过程中对象数据(对象__dict__
内容)丢失了。
So I tried another approach: 所以我尝试了另一种方法:
def refresh(obj, memo=None):
if memo is None:
memo = {}
d = id(obj)
if d in memo:
return
memo[d] = None
try:
obj.__class__ = getattr(sys.modules[obj.__class__.__module__],
obj.__class__.__name__)
except TypeError:
return
for item in obj.__dict__.itervalues():
if isinstance(item, dict):
for k, v in item.iteritems():
refresh(k, memo)
refresh(v, memo)
elif isinstance(item, (list, tuple)):
for v in item:
refresh(v, memo)
else:
refresh(item, memo)
And surprisingly it works ! 而且令人惊讶的是它有效! After calling refresh() on my objects, the new code becomes effective, without need to recreate them. 在我的对象上调用refresh()之后,新代码将生效,而无需重新创建它们。
But I'm not sure if this is the correct way to traverse an object ? 但是我不确定这是否是遍历对象的正确方法吗? Is there a better way to traverse an object's components ? 有没有更好的方法遍历对象的组件?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.