内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用
我有一个动物类,它有几个属性,比如:
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的方法吗?
在这种简单的情况下,您可以使用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