Zoler1337
Zoler1337

Reputation: 116

How to update a class init argument value?

I'm trying to use a constant variable be the basis for two different classes. Then I want to use one class to update the variable and then also make that update affect the two classes. How to go about this? Is it possible?

If I just simply update the variable then from what I can tell the objects A and B are already created thus they still have the old var1 value so that doesn't work.

Help appreciated!

class A:
    def__init__(self, var1):
         self.var1 = var1

    def function A:
         #Use self.var1 to do something

class B:
    def __init__(self, var1):
          self.var1 = var1

 def function B:
       #Update self.var1

var1 = 123
A = A(var1)
B = B(var1)

Upvotes: 0

Views: 1048

Answers (1)

quamrana
quamrana

Reputation: 39354

Variables in python are implemented as resettable references, so any assignment resets the reference, which does not affect any other variables. This is why something like: var1 = 456 would not affect your objects.

One way round that is to introduce some indirection:

class A:
    def __init__(self, var1):
         self.var1 = var1

    def __str__(self):
         return f'A:{self.var1}'

class B:
    def __init__(self, var1):
          self.var1 = var1

    def __str__(self):
         return f'B:{self.var1}'

var1 = [123]   # a list containing an int
a = A(var1)
b = B(var1)
print(a)
print(b)

var1[0] = 456
print(a)
print(b)

Output:

A:[123]
B:[123]
A:[456]
B:[456]

Upvotes: 2

Related Questions