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)

3
  • 2
    stackoverflow.com/questions/192109/… Commented Dec 9, 2015 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'] ? Commented Dec 9, 2015 at 12:16
  • 1
    is this what you are looking for ? stackoverflow.com/a/23689767/2652580 Commented Dec 9, 2015 at 12:23

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Can you give an example about what you said about __str__?
what is your expected output ?
This output, @ZdaR : {'param1': 17, 'param2': 3}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.