打印Python类的所有属性

259 投票
6 回答
452384 浏览
提问于 2025-04-16 17:28

我有一个叫做Animal的类,它里面有几个属性,比如:


class Animal(object):
    def __init__(self):
        self.legs = 2
        self.name = 'Dog'
        self.color= 'Spotted'
        self.smell= 'Alot'
        self.age  = 10
        self.kids = 0
        #many more...

现在我想把这些属性都打印到一个文本文件里。我现在的方法有点笨拙,像这样:


animal=Animal()
output = 'legs:%d, name:%s, color:%s, smell:%s, age:%d, kids:%d' % (animal.legs, animal.name, animal.color, animal.smell, animal.age, animal.kids,)

有没有更好的Python方式来做到这一点呢?

6 个回答

76

也许你在找这样的东西?

    >>> class MyTest:
        def __init__ (self):
            self.value = 3
    >>> myobj = MyTest()
    >>> myobj.__dict__
    {'value': 3}
122

另一种方法是调用 dir() 函数(可以查看 https://docs.python.org/2/library/functions.html#dir)。

a = Animal()
dir(a)   
>>>
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__',
 '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', 
 '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 
 '__weakref__', 'age', 'color', 'kids', 'legs', 'name', 'smell']

需要注意的是,dir() 会尝试访问所有可以访问的属性。

然后你可以通过双下划线来过滤这些属性,例如:

attributes = [attr for attr in dir(a) 
              if not attr.startswith('__')]

这只是使用 dir() 的一种可能性示例,具体的使用方法请查看其他答案。

466

在这个简单的例子中,你可以使用 vars()

an = Animal()
attrs = vars(an)
# {'kids': 0, 'name': 'Dog', 'color': 'Spotted', 'age': 10, 'legs': 2, 'smell': 'Alot'}
# now dump this in some way or another
print(', '.join("%s: %s" % item for item in attrs.items()))

如果你想把Python对象存储到硬盘上,你可以看看 shelve — Python对象持久化

撰写回答