0

EDIT: a solution is in this answer: How to use a dot “.” to access members of dictionary?

When using a dict:

d = dict()
d['param1'] = 17
d['param2'] = 3

it's easy to print it with print json.dumps(d). When using an object / class:

class z: 
    pass
z.param1 = 17
z.param2 = 3

I can't manage to print all the attributes of z, neither with print json.dumps(z), nor with print z. How to do it?


Sidenote but important: why do I want to use a class / object to store parameters, when it would be logical to use a dict? Because z.param1 is much shorter and handy to write than z['param1'], especially with my (french) keyword [, ], 'are quit long to write because ALT+GR+5 (let's say 2 seconds instead of 0.5, but this really matters when you have a long code with many variables)

Community
  • 1
  • 1
Basj
  • 41,386
  • 99
  • 383
  • 673
  • 2
    http://stackoverflow.com/questions/192109/is-there-a-function-in-python-to-print-all-the-current-properties-and-values-of – Termi Dec 09 '15 at 12:10
  • @Anil Or something else : would there be a short hack (by subclassing `dict`) for accessing a dict with `d.param1` instead of `d['param1']` ? – Basj Dec 09 '15 at 12:16
  • 1
    is this what you are looking for ? http://stackoverflow.com/a/23689767/2652580 – Termi Dec 09 '15 at 12:23

1 Answers1

3

You may simply use __dict__ on a class instance to get the attributes in the form of dict object as:

>>> z.__dict__
>>> {'param1': 17, '__module__': '__main__', 'param2': 3, '__doc__': None}

However, if you need to remove the __xxx__ inbuilt methods then you may need to specify the __str__ method inside the class.

ZdaR
  • 22,343
  • 7
  • 66
  • 87