Idr Idr - 1 year ago 115
Python Question

Print all properties of a Python Class

I have a class Animal with several properties like:

class Animal(object):
def __init__(self):
self.legs = 2 = 'Dog'
self.color= 'Spotted'
self.smell= 'Alot'
self.age = 10 = 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:

output = 'legs:%d, name:%s, color:%s, smell:%s, age:%d, kids:%d' % (animal.legs,, animal.color, animal.smell, animal.age,,)

Is there a better Pythonic way to do this?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download