打印Python类的所有属性

时间:2011-05-11 19:51:36

标签: python oop

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


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方法吗?

6 个答案:

答案 0 :(得分:251)

在这种简单的情况下,您可以使用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

答案 1 :(得分:64)

另一种方法是调用dir()函数(参见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']

请注意,dir()会尝试访问可能达到的任何属性。

然后您可以访问属性,例如通过双下划线过滤:

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

这只是dir()可以做什么的一个示例,请查看其他答案,了解正确的方法。

答案 2 :(得分:50)

也许你正在寻找这样的东西?

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

答案 3 :(得分:7)

尝试ppretty

from ppretty import ppretty


class Animal(object):
    def __init__(self):
        self.legs = 2
        self.name = 'Dog'
        self.color= 'Spotted'
        self.smell= 'Alot'
        self.age  = 10
        self.kids = 0


print ppretty(Animal(), seq_length=10)

输出:

__main__.Animal(age = 10, color = 'Spotted', kids = 0, legs = 2, name = 'Dog', smell = 'Alot')

答案 4 :(得分:6)

这是完整的代码。结果正是你想要的。

Stop-Process

答案 5 :(得分:3)

试试beeprint

它打印的内容如下:

instance(Animal):
    legs: 2,
    name: 'Dog',
    color: 'Spotted',
    smell: 'Alot',
    age: 10,
    kids: 0,

我认为这正是你所需要的。