打印Python类的所有属性

Idr*_*Idr 150 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...
Run Code Online (Sandbox Code Playgroud)

我现在想要将所有这些属性打印到文本文件中.我现在这样做的丑陋方式就像:


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,)
Run Code Online (Sandbox Code Playgroud)

有更好的Pythonic方法吗?

Joc*_*zel 272

在这个简单的例子中,您可以使用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())
Run Code Online (Sandbox Code Playgroud)

如果你想在磁盘上存储Python对象,你应该看看shelve - Python对象持久性.

  • 只有使用`__dict__`来存储属性(这是Python对象的默认行为)时,`vars`才有效.如果您使用`__slots__`,请参阅@ BasicWolf的答案 (8认同)
  • ``类型错误:vars() 参数必须具有 __dict__ 属性`` (4认同)
  • 哦,太好了,从来没有那样使用过`vars`!我以为它就像`locals()`一样,不知道您可以在类/模块上使用它。很有用! (2认同)

Zau*_*bov 68

另一种方法是调用该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']
Run Code Online (Sandbox Code Playgroud)

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

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

attributes = [attr for attr in dir(a) 
              if not attr.startswith('__')]
Run Code Online (Sandbox Code Playgroud)

这只是可以做的事情的一个例子dir(),请检查其他答案以获得正确的方法.

  • 这可能是正确的方法,但应该指出它正在做的是打印出*属性*,而不是在Python中的新式类中称为属性的东西,并且它是基于*实例*来实现的.一个类,而不是类本身(因为这些属性在创建类实例并且调用__init __()之前不存在).此外,如果稍后创建任何其他属性,显然也会省略它们. (3认同)

Urj*_*jit 56

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

    >>> class MyTest:
        def __init__ (self):
            self.value = 3
    >>> myobj = MyTest()
    >>> myobj.__dict__
    {'value': 3}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,因为这为您提供了一个字典,如果您想要快速的 API 参考 `print(o.__dict__.keys())`,您也可以只查看键。 (3认同)

Sym*_*mon 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)
Run Code Online (Sandbox Code Playgroud)

输出:

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


Jae*_* So 6

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

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

if __name__ == '__main__':
    animal = Animal()
    temp = vars(animal)
    for item in temp:
        print item , ' : ' , temp[item]
        #print item , ' : ', temp[item] ,
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

205978 次

最近记录:

7 年,8 月 前