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 :(得分: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
答案 1 :(得分:2)
严格地说,你不能(不修改Node
类)。 __dict__
不保留对原始对象的引用。您可以通过复制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
。
答案 2 :(得分: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
但请注意,这与复制对象不同,我觉得你可能会遇到各种奇怪的问题(仅举一例:没有调用对象的构造函数)。