对于新样式的类,您可以循环类实例的dict_u2;中的条目: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)]
因为这个字典只是一个字典,所以你可以循环使用它来选择你需要的条目(在上面的例子中,我过滤掉了以下划线开头的条目,但是它可以是您想要的任何条件)。您可以使用内置命令vars获得相同的信息:
^{pr2}$
你可以再次选择你需要的钥匙。在
您还可以使用inspect模块对对象进行更详细的检查:import inspect
print inspect.getmembers(Example())
#[('__class__', ), ('__delattr__', ), ('__dict__', {'four': 4, 'three': 3, 'two': 2, 'one': 1}), ('__doc__', None), ('__format__', ), ('__getattribute__', ), ('__hash__', ), ('__init__', >), ('__module__', '__main__'), ('__new__', ), ('__reduce__', ), ('__reduce_ex__', ), ('__repr__', ), ('__setattr__', ), ('__sizeof__', ), ('__str__', ), ('__subclasshook__', ), ('__weakref__', None), ('four', 4), ('members', >), ('one', 1), ('three', 3), ('two', 2)]