Inheritance does not work this way in Python. However, I think your problem is mutability rather than inheritance itself. (You did not apply inheritance, I said these because you used it as a tag and in the title.)
Try it like this.
class a():
def __init__(self):
self.x = [5]
class b():
def __init__(self, r):
self.y = r
def chg(self, a):
self.y = a
m = a()
n = b(m.x)
n.y[0] = 99
print m.x
# Gives 99
This way, you only create one list, and use it with two different classes.
Note: You can think this as the pass by reference property in C-type languages.
Just to keep in mind, every assignment in Python is pass by reference because Python handles variables different than those languages. Read more about it. (This does not affect mutability.)
Edit: I see you edited you question. Now let me explain why your code does not work as you expected.
Mutability means you can change the elements inside a container, without assigning it to a new address in memory.
When you do,
n.y = ["c", "d"]
You do not change the list,(So you do not mutate the list) you just assign a new list to that variable name. To change the original list, you must alter every element by using list[index]
, so the element would be changed, but the list will be the same list. So you can do this
m = a()
n = b(m.x)
new_list = ["c", "d"]
for i, elem in enumerate(new_list):
# This way you change every element one-by-one.
n.y[i] = elem
print m.x
If you are not familiar with enumerate
, study it immediately. But if you want to use simpler code(And more similar to C implementation.) You can make the assignments like this,
for i in range(len(new_list)):
n.y[i] = new_list[i]