For the life of me I cannot explain why this is happening:
class Foo():
def __init__(self):
self.x = 'x'
class Bar():
def __init__(self):
self.items = {}
bar = Bar()
bar.items['a'] = Foo()
foo_dict = bar.items['a'].__dict__
bar_dict = bar.__dict__
print(bar.items) # {'a': <__main__.Foo object at 0x7ff68f217690>}
bar_dict['items']['a'] = foo_dict
print(bar.items) # {'a': {'x': 'x'}}
Why does bar_dict['items']['a'] = foo_dict
change the original Foo()
instance?
Edit: thanks for all the replies guys. I understand it better now. It can be shown more succinctly by:
class Bar():
def __init__(self):
self.test = 'old'
bar = Bar()
bar_dict = bar.__dict__
print(id(bar.test), id(bar_dict['test'])) # ids are equal
bar_dict['test'] = 'new'
print(bar.test) # new
I guess I still don't understand why this necessarily works though.