打印Python类的所有属性

2024-03-29 12:44:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类动物,有几个特性,比如:


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,)

有没有更好的方法来做这件事?


Tags: nameselfageobjectinitdef特性class
3条回答

另一种方法是调用^{}函数(请参见https://docs.python.org/2/library/functions.html#dir)。

a = Animal()
dir(a)   
>>>
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__',
 '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', 
 '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 
 '__weakref__', 'age', 'color', 'kids', 'legs', 'name', 'smell']

注意,^{}尝试访问任何可能访问的属性。

然后您可以访问属性,例如使用双下划线进行筛选:

attributes = [attr for attr in dir(a) 
              if not attr.startswith('__')]

这只是一个关于^{}可以做什么的例子,请检查其他答案以了解正确的方法来做这件事。

在这个简单的例子中,您可以使用^{}

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

也许你在找这样的东西?

    >>> class MyTest:
        def __init__ (self):
            self.value = 3
    >>> myobj = MyTest()
    >>> myobj.__dict__
    {'value': 3}

相关问题 更多 >