python - 打印 Python 类的所有属性

标签 python oop

我有一个类 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/

相关文章:

java - 构建Java控制台程序的正确方法

python - 我应该传递对象还是在构造函数中构建它?

oop - 这里需要抽象类吗?

python - 对打开文件的脚本进行单元测试

python - 如何更快地将更大的.sql文件执行到数据库?

python - 将 df 列中的值转换为 True/False

language-agnostic - 为什么不能创建抽象类的对象?

python - 如何在另一个模块中设置断点(不要在函数定义行设置,如果你想在函数开始执行时中断)

python - 不支持 None 值,Keras LSTM 适合

python - 如何在 Python 中从该类中创建嵌套类的实例?