Python - 返回方法修改的所有 self.* 变量
有没有什么方法可以返回在Python中被某个方法修改过的所有self
变量呢?
举个例子,我有一个方法修改了二十个self
变量,我想在方法结束时返回self.variable1, self.variable2...
。
这是我现在的做法(这是一个更大方法的最后部分):
return (self.p1_error, self.p1,
self.p2_error, self.p2,
self.p3_error, self.p3,
self.p4_error, self.p4,
self.p5_error, self.p5,
self.p6_error, self.p6,
self.p7_error, self.p7,
self.p8_error, self.p8,
self.p9_error, self.p9,
self.p10_error, self.p10)
有没有更简洁的方法呢?
2 个回答
3
对于新式类,你可以通过类实例的 __dict__ 来遍历里面的内容:
class Example(object):
def __init__(self):
self.one = 1
self.two = 2
self.three = 3
self.four = 4
def members(self):
all_members = self.__dict__.keys()
return [ (item, self.__dict__[item]) for item in all_members if not item.startswith("_")]
print Example().members()
#[('four', 4), ('three', 3), ('two', 2), ('one', 1)]
因为 __dict__ 就像一个字典,你可以遍历它来选择你需要的项目(在上面的例子中,我过滤掉了以下划线开头的项目,但你可以根据任何标准来选择)。你也可以使用内置的命令 vars
来获取相同的信息:
test = Example()
print vars(test):
# {'four': 4, 'three': 3, 'two': 2, 'one': 1}
同样,你可以选择你需要的键。
你还可以使用 inspect
模块来更详细地检查一个对象:
import inspect
print inspect.getmembers(Example())
#[('__class__', <class '__main__.Example'>), ('__delattr__', <method-wrapper '__delattr__' of Example object at 0x000000000243E358>), ('__dict__', {'four': 4, 'three': 3, 'two': 2, 'one': 1}), ('__doc__', None), ('__format__', <built-in method __format__ of Example object at 0x000000000243E358>), ('__getattribute__', <method-wrapper '__getattribute__' of Example object at 0x000000000243E358>), ('__hash__', <method-wrapper '__hash__' of Example object at 0x000000000243E358>), ('__init__', <bound method Example.__init__ of <__main__.Example object at 0x000000000243E358>>), ('__module__', '__main__'), ('__new__', <built-in method __new__ of type object at 0x000000001E28F910>), ('__reduce__', <built-in method __reduce__ of Example object at 0x000000000243E358>), ('__reduce_ex__', <built-in method __reduce_ex__ of Example object at 0x000000000243E358>), ('__repr__', <method-wrapper '__repr__' of Example object at 0x000000000243E358>), ('__setattr__', <method-wrapper '__setattr__' of Example object at 0x000000000243E358>), ('__sizeof__', <built-in method __sizeof__ of Example object at 0x000000000243E358>), ('__str__', <method-wrapper '__str__' of Example object at 0x000000000243E358>), ('__subclasshook__', <built-in method __subclasshook__ of type object at 0x0000000002255AC8>), ('__weakref__', None), ('four', 4), ('members', <bound method Example.members of <__main__.Example object at 0x000000000243E358>>), ('one', 1), ('three', 3), ('two', 2)]
1
在这个方法里保持一个列表,每当有任何变量发生变化时,就把这个变化添加到列表里,最后在方法结束时返回这个列表。