打印 Python 类的所有属性 [英] Print all properties of a Python Class

查看:41
本文介绍了打印 Python 类的所有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类 Animal 有几个属性,例如:

I have a class Animal with several properties like:


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...

我现在想将所有这些属性打印到一个文本文件中.我现在做的丑陋的方式是:

I now want to print all these properties to a text file. The ugly way I'm doing it now is like:


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 方法来做到这一点?

Is there a better Pythonic way to do this?

推荐答案

在这个简单的例子中你可以使用 vars():

In this simple case you can use 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 对象持久化.

If you want to store Python objects on the disk you should look at shelve — Python object persistence.

这篇关于打印 Python 类的所有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆