I write a program in Python. I Have class A. one of its variables,v, is an instance of another class, B:
class A:
def __init__(self):
self.v = B()
the class B in in the form of:
class B:
def __init__(self):
self.list = [1,2,3]
def function(self):
self.list[2] = 1
I create an instance x=A(), put it in a list g (g=[x]) and then change one of the variables in x.v by printing g[0].v.function(). However, when I ask the computer to print g[0].v.list, it prints [1,2,3] rather then [1,2,1]. What can be the reason?
Thank you.
asked Jan 29, 2013 at 18:03
user1767774
1,8253 gold badges26 silver badges34 bronze badges
-
1Are you sure? The code you posted would do exactly that.Martijn Pieters– Martijn Pieters2013年01月29日 18:05:52 +00:00Commented Jan 29, 2013 at 18:05
-
Is this the actual code that is having a problem? This code works as described.Silas Ray– Silas Ray2013年01月29日 18:09:56 +00:00Commented Jan 29, 2013 at 18:09
1 Answer 1
Works for me:
class A:
def __init__(self):
self.v = B()
class B:
def __init__(self):
self.list = [1,2,3]
def function(self):
self.list[2] = 1
x = A()
g = [x]
print g[0].v.function()
print g[0].v.list
output:
None
[1, 2, 1]
answered Jan 29, 2013 at 18:06
mgilson
312k70 gold badges657 silver badges723 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py