【发布时间】:2011-08-23 14:40:18
【问题描述】:
我有一个 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 方式来做到这一点?
【问题讨论】:
-
您是否尝试搜索与定位类的所有属性相关的问题?被问过了。以stackoverflow.com/questions/1215408/… 为例。
-
@S.Lott:虽然 OP 专门询问了类的属性,但从他们的示例代码中我认为很明显他们没有考虑数据描述符。