1

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?

brokendreams
  • 827
  • 2
  • 10
  • 29
  • I think you meant `self.name = 'jim'` and `self.age = 2`. – Robᵩ Aug 19 '16 at 23:29
  • Depends. Do you care about only what you have defined visibly in your class or do you want literally every property and method including those inherited from your own parent classes and built-in objects? – Two-Bit Alchemist Aug 19 '16 at 23:30
  • If you assign those vars to `self` then you can use `print(him.__dict__)`. – double_j Aug 19 '16 at 23:31

1 Answers1

1

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}
vsminkov
  • 10,912
  • 2
  • 38
  • 50
  • Alternatively, substitute `vars(him)` to `him.__dict__`. Ref: http://stackoverflow.com/questions/21297203/use-dict-or-vars – Robᵩ Aug 20 '16 at 00:11