chrisvp chrisvp - 3 months ago 6
Python Question

python use lazy assignment when passing lists to methods

I have a python class A and its child B. I make an object of class B passing some list-type arguments, which are appended in B and the result stored in class A. I would like to be able to change one of those initial arguments and see the change reflected without further ado. Let me explain with an example:

class A():
def __init__(self,data):
self.a=data

class B(A):
def __init__(self,x,y):
self.x=x
self.y=y
A.__init__(self,self.x+self.y)

def change_x(self,x):
self.x = x


Now, wen i run

test = B([1, 2], [3,4])
print(test.a)


I obviously get [1,2,3,4]. If I change part of the list as follows:

test.change_x([3,4])
print(test.a)


I would like to get [3,4,3,4], instead of course, I receive [1,2,3,4]. Of course test.a is only evaluated during instantiation.

I understand why this is not the case and I read about generators but don't manage to figure out how to implement this. I don't want to end up with an iterable that i can only iterate once.

Could anyone help me? A clean way to solve this?

Answer

You need to implement it "manually". For example, like so:

class B(A):
    def __init__(self,x,y):
        self.x=x
        self.y=y
        self.spread_changes()

    def change_x(self,x):
        self.x = x
        self.spread_changes()

    def spread_changes(self):
        A.__init__(self,self.x+self.y)