0

I have a class instance instance_1.

How can I create another variable that always holds an up to date reference to instance_1?

This one does not work:

class my_class():
    def __init__(self):
        self.my_a = 44

    def update_my_a(self):
        self.my_a = 33


instance_1 = my_class()
my_var = instance_1.my_a
instance_1.update_my_a()
print(instance_1.my_a)
>>33
print(my_var)
>>44
  • 1
    Everything is a reference in Python. However, assignment merely rebinds the reference to the name. So, make your value a mutable type (class Val: ...) then mutate it in `update_my_a`, e.g. `self.my_a_val.set(33)` – juanpa.arrivillaga Mar 29 '18 at 04:52

1 Answers1

1

You can create object reference like below

class my_class():
    def __init__(self):
        self.my_a = 44

    def update_my_a(self):
        self.my_a = 33


instance_1 = my_class()
my_var = instance_1
instance_1.update_my_a()
print(instance_1.my_a)
>33
print(my_var.my_a)
>33
Jay Shankar Gupta
  • 5,918
  • 1
  • 10
  • 27