-1

I am having some trouble using the function __dict__ with some object in python. What I wanted to do was to create a dictionary that showing all the attribute of all the sub-object in the original object as well. But when I called the function, rather than having the oject it self, I will get something like:

<Attribute><models.Object instance at 0x0000000002EF4288></Attribute>

I am new to python so I am not sure how things work. My objective to return the content of Object instance in the form of dictionary as well. Thank you guys in advance.

Yes, Thanks to bren for pointing out the mistake, the exact output is just this:

{'Attribute': <models.Object instance at 0x0000000002EF4288>}

the operation I did was just wrapper.__dict__

The class wrapper is:

class wrapper:
    def wrapper(self, object):
        self.Attribute = object

while object contains other attributes as wells and I want to put them in one dict.

  • 3
    Python won't return XML like that just from calling `dict` or reading the `__dict__` attribute. Please post the actual code you are using and its output. – BrenBarn May 27 '13 at 05:10
  • Propably the same question: http://stackoverflow.com/questions/61517/python-dictionary-from-an-objects-fields – diegoperini May 27 '13 at 05:12
  • If you're new to Python it may be better not to try to simulate dictionaries. Just write the program in a straightforward way. – poolie May 27 '13 at 05:16
  • Yup fixed the output. I wished I could but the program I am working on required me to derive nested dict out of a nested object. – Just Another Hungry Beginner May 27 '13 at 05:29

1 Answers1

0

You may be looking for inspect.getmembers():

import inspect
from pprint import pprint
class Foo():
    def __init__(self):
        self.foo = 'bar'
    def foobar(self):
        pass

instance = Foo()

pprint(dict(inspect.getmembers(instance)))
>>> 
{'__doc__': None,
 '__init__': <bound method Foo.__init__ of <__main__.Foo instance at 0x7b07b0>>,
 '__module__': '__main__',
 'foo': 'bar',
 'foobar': <bound method Foo.foobar of <__main__.Foo instance at 0x7b07b0>>}
qwwqwwq
  • 6,999
  • 2
  • 26
  • 49