2013-05-27 34 views
-1

我在使用函數__dict__和python中的某些對象時遇到了一些麻煩。我想要做的是創建一個字典,顯示原始對象中所有子對象的所有屬性。但是,當我打電話的功能,而不是讓oject它的自我,我會得到這樣的:窮舉詞典在Python中的使用

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

我是新來的蟒蛇,所以我不知道事情是如何工作的。我的目標是以字典的形式返回Object實例的內容。謝謝你們提前。

是,由於布倫您指出的錯誤,精確的輸出僅僅是這樣的:

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

我所做的工作只是wrapper.__dict__

類包裝是:

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

object包含其他屬性,我想把它們放在一個字典中。

+3

Python將不只是從調用'dict'或讀取'__dict__'屬性返回XML這樣的。請發佈您正在使用的實際代碼及其輸出。 – BrenBarn

+0

顯然是同樣的問題:http://stackoverflow.com/questions/61517/python-dictionary-from-an-objects-fields – diegoperini

+0

如果你是新來的Python,最好不要試圖模擬字典。只需直接編寫程序即可。 – poolie

回答

0

你可能會尋找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>>}