打印Python类的所有属性 [英] Print all properties of a Python Class
本文介绍了打印Python类的所有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个Animal类,它具有以下几种属性:
I have a class Animal with several properties like:
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...
我现在想将所有这些属性打印到一个文本文件中.我现在做的丑陋方式就像:
I now want to print all these properties to a text file. The ugly way I'm doing it now is like:
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方式来做到这一点?
Is there a better Pythonic way to do this?
推荐答案
在这种简单情况下,您可以使用 vars()
:
In this simple case you can use 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()))
If you want to store Python objects on the disk you should look at shelve — Python object persistence.
这篇关于打印Python类的所有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文