我有一个类 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 .
关于python - 打印 Python 类的所有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5969806/