为python中方法中使用的每个变量设置对象属性

2024-10-04 11:28:33 发布

您现在位置:Python中文网/ 问答频道 /正文

如何将对象方法中的所有局部变量(几乎)设置为该对象的属性?在

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

Tags: 对象方法selfobjhelloworld属性object
2条回答

Python update object from dictionary的启发,我提出了以下建议:

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 debugger可以让您检查局部变量,因此没有必要用随机实例属性污染对象。在

另外,如果多个方法使用相同的局部变量名,则该方法不起作用,因为方法可能会覆盖某些实例属性,从而使对象的状态处于不明确的状态。在

另外,您的解决方案与DRY principle背道而驰,因为您必须在每个return之前添加代码。在

另一个缺点是,在方法执行过程中,您经常想知道多个地方局部变量的状态,而这对于您的答案是不可能的。在

如果您真的想手动保存局部变量,那么类似这样的方法可能比您的解决方案要好得多:

import inspect
from collections import defaultdict



class LogLocals(object):

    NO_BREAK_POINT = object()

    def __init__(self):
        self.__locals = defaultdict(defaultdict(list))

    def register_locals(self, local_vars, method_name=None, 
                              break_point=NO_BREAK_POINT):
        if method_name is None:
            method_name = inspect.currentframe(1).f_code.co_name
        self.__locals[method_name][break_point].append(local_vars)

    def reset_locals(self, method_name=None, break_point=NO_BREAK_POINT,
                           all_=False):
        if method_name is None:
            method_name = inspect.currentframe(1).f_code.co_name
        if all_:
            del self.__locals[method_name]
        else:
            del self.__locals[method_name][point]

    def get_locals(self, method_name, break_point=NO_BREAK_POINT):
        return self.__locals[method_name][break_point]

您只需从它继承,并在需要保存状态时调用register_locals(locals())。它还允许区分“断点”,最重要的是它不会污染实例。 此外,它还区分了返回状态的list而不是最后一个状态的不同调用。在

如果要通过属性访问某些调用的局部变量,只需执行以下操作:

^{pr2}$

不管怎样,我相信这没什么用。你应该使用python调试器。在

相关问题 更多 >