Print all properties of a Python Class [duplicate]
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,)
Is there a better Pythonic way to do this?
Solution 1:
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()))
If you want to store Python objects on the disk you should look at shelve — Python object persistence.
Solution 2:
Another way is to call the dir()
function (see 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']
Note, that dir()
tries to reach any attribute that is possible to reach.
Then you can access the attributes e.g. by filtering with double underscores:
attributes = [attr for attr in dir(a)
if not attr.startswith('__')]
This is just an example of what is possible to do with dir()
, please check the other answers for proper way of doing this.