user1767774
user1767774

Reputation: 1825

object inside another object in python

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.

Upvotes: 0

Views: 15908

Answers (1)

mgilson
mgilson

Reputation: 309831

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]

Upvotes: 4

Related Questions