Suppose I have in python this object
class Foo:
def __init__(self, val):
self.val = val
and these two variables
a=Foo(5)
b=a
both b
and a
refer to the same instance of Foo()
, so any modification to the attribute .val
will be seen equally and synchronized as a.val
and b.val
.
>>> b.val
5
>>> b.val=3
>>> a.val
3
Now suppose I want to say a=Foo(7)
. This will create another instance of Foo, so now a
and b
are independent.
My question is: is there a way to have b
readdressed automatically to the new Foo() instance, without using an intermediate proxy object? It's clearly not possible with the method I presented, but maybe there's some magic I am not aware of.
As Aaron points out, there may be very hacky and fragile solutions but there is likely nothing that would be guaranteed to work across all Python implementations (e.g. CPython, IronPython, Jython, PyPy, etc). But why would one realistically want to do something that is so contrary to the design and idiomatic use of the language when there are simple idiomatic solutions available? Calling a class object typically returns an instance object. Names are bound to that object. Rather than trying to fight the language by coming up with hacks to track down references to objects in order to update bindings, the natural thing would be to design a mutable instance object, if necessary using a simple wrapper around an existing class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With