2012-03-22 29 views
2
class Node(object): 
    def __init__(self, data): 
     self.data = data 

if __name__ == "__main__": 
    a = Node(5) 
    print a # prints __main__.Node object at 0x025C7530 
    print a.__dict__ # how can I turn this back into the previous line? 

反正有沒有把字典回到對象中?如何將對象.__ dict__再次轉換爲對象本身?

+0

你想用這個做什麼?如果該屬性不是隻讀的,則最終會產生無限遞歸對象。 – Blender 2012-03-22 05:24:42

+0

我使用的函數「gc.get_referrers」只返回對象的字典而不是對象。 – Jae 2012-03-22 05:27:20

回答

3

對於某些類型的對象,你可以得到一個相同的對象(而不是對象本身,而是一個副本):

class Node(object): 
    def __init__(self, data): 
     self.data = data 

if __name__ == "__main__": 
    a = Node(5) 
    a = a.__dict__ #whoops, now I lost the object, I just have the dict 
    b = Node.__new__(Node) # make a new empty object 
    b.__dict__ = a.copy() # copy in the dict 
    # copy because there might still a reference to the object elsewhere 
    # if you want changes to b to affect a, then don't copy just assign 
    print b.__dict__ 
    print b 
2

嚴格來說,你不能(沒有修改Node類)。 __dict__不保留對原始對象的引用。您可以通過複製字典有所建樹類似

n1 = Node(5) 
n2 = Node.__new__(Node) # object created but not initiated. 
n2.__dict__ = n1.__dict__ 
n1.foo = 'something fooish' 

print n1.foo == n2.foo #True 

不幸的是,n1 != n2

0

我只知道這是可能的老式類在Python 2:

class Ode(): # not derived from object 
    def __init__(self, data): 
     self.data = data 

>>> o = Ode(6) 
>>> o.data 
6 

>>> import new 
>>> od = o.__dict__ 
>>> od 
{'data': 6} 
>>> new.instance(Ode, od).data 
6 
>>> new.instance(Ode, {'data': 666}).data 
666 

但請注意,這不同於複製對象,我覺得你可能會遇到各種奇怪的問題(只提一個:對象的構造函數沒有被調用)。