python - 打印 Python 类的所有属性

我有一个类 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,)

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

最佳答案

在这个简单的例子中,您可以使用 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 object persistence .

https://stackoverflow.com/questions/5969806/

相关文章:

c - 如何在linux c程序中获取pthread的线程ID?

python - 在批处理文件中休眠

python - Anaconda 与 miniconda

linux - 如何 RSYNC 单个文件?

python - 如何在 Windows 上使用 Python 3 连接到 MySQL?

python - 在 Python 中 Ping 服务器

linux - Shell - 将变量内容写入文件

c - 如何使用 GDB 修改内存内容?

unix - 如何交错来自两个文本文件的行

python - 在 IPython 中自动重新加载模块