Python - 返回由方法修改的所有self。*变量

时间:2014-07-31 05:03:18

标签: python class python-2.7 methods

有没有办法返回python中方法修改过的所有self变量?

例如,我有一个修改了20个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 个答案:

答案 0 :(得分:1)

对于新式类,您可以遍历类实例的__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 :(得分:1)

在方法中维护一个列表,每当更改任何变量时,将其附加到列表中, 返回方法末尾的列表。