No need for wrapper classes!
Just make self.foo
a property that accesses the value in your dictionary:
class Bar:
def __init__(self, foo_):
self.foo_dict = {}
self.foo = foo_
@property
def foo(self):
return self.foo_dict["foo_key"]
@foo.setter
def foo(self, value):
self.foo_dict["foo_key"] = value
def show(self):
print("foo={} ; foo_dict['foo_key']={}".format(
self.foo, self.foo_dict["foo_key"]))
b = Bar(1)
b.show()
b.foo = 2
b.show()
b.foo_dict["foo_key"] = 3
b.show()
See this code running on ideone.com
Properties look to the outside like normal instance member fields, but they are really custom functions that could do anything. This way the two foo(...)
methods are called when the foo
property is accessed. The one decorated with @property
is the getter and the one decorated with @PROPERTYNAME.setter
is obviously the setter. You could also restrict read or write access to the property by simply omitting one of the property methods.
Here, they redirect all actions to the dictionary. That way you have exactly one instance of a simple mutable variable, but multiple ways to access it.
The example above would result in this output:
foo=1 ; foo_dict['foo_key']=1
foo=2 ; foo_dict['foo_key']=2
foo=3 ; foo_dict['foo_key']=3
So as we can see, no matter whether we change the value in the dictionary or through the property, both names always point to the same variable.