我有一个类动物,有几个特性,比如:
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,)
有没有更好的方法来做这件事?
另一种方法是调用^{} 函数(请参见https://docs.python.org/2/library/functions.html#dir)。
注意,^{} 尝试访问任何可能访问的属性。
然后您可以访问属性,例如使用双下划线进行筛选:
这只是一个关于^{} 可以做什么的例子,请检查其他答案以了解正确的方法来做这件事。
在这个简单的例子中,您可以使用^{} :
如果要在磁盘上存储Python对象,应该查看shelve — Python object persistence。
也许你在找这样的东西?
相关问题 更多 >
编程相关推荐