class Obj(object):
def do_something(self):
localstr = 'hello world'
localnum = 1
#TODO store vars in the object for easier inspection
x = Obj()
x.do_something()
print x.localstr, x.localnum
class Obj(object):
def do_something(self):
localstr = 'hello world'
localnum = 1
# store vars in the object for easier inspection
l = locals().copy()
del l['self']
for key,value in l.iteritems():
setattr(self, key, value)
x = Obj()
x.do_something()
print x.localstr, x.localnum
受Python update object from dictionary的启发,我提出了以下建议:
已经有一个python debugger可以让您检查局部变量,因此没有必要用随机实例属性污染对象。在
另外,如果多个方法使用相同的局部变量名,则该方法不起作用,因为方法可能会覆盖某些实例属性,从而使对象的状态处于不明确的状态。在
另外,您的解决方案与DRY principle背道而驰,因为您必须在每个
return
之前添加代码。在另一个缺点是,在方法执行过程中,您经常想知道多个地方局部变量的状态,而这对于您的答案是不可能的。在
如果您真的想手动保存局部变量,那么类似这样的方法可能比您的解决方案要好得多:
您只需从它继承,并在需要保存状态时调用
register_locals(locals())
。它还允许区分“断点”,最重要的是它不会污染实例。 此外,它还区分了返回状态的list
而不是最后一个状态的不同调用。在如果要通过属性访问某些调用的局部变量,只需执行以下操作:
^{pr2}$不管怎样,我相信这没什么用。你应该使用python调试器。在
相关问题 更多 >
编程相关推荐