brokendreams brokendreams - 3 months ago 9
Python Question

Print attribute of class based on attribute name

Is there a way to print out all the attributes of a python object along with their values

For example, for the following class and object

class man:
def __init__(self):
name = "jim"
age = 2

him = man()


I want to print out all the attributes of the object "him" as well as their values. I want some kind of code that acts like the following

for variable_name of him:
print variable_name," : ",him.variable_name


should print out

name : jim
age : 2


Is there any way to do that in python?

Answer

First of all you need to properly define fields in your object:

class man(objet):
    def __init__(self):
        self.name = "jim"
        self.age = 2

Then you can use object.__dict__:

>>> him = man()
>>> himp.__dict__
{'name': 'jim', 'age': 2}
Comments