Get variable from class inside another class - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Get variable from class inside another class (/thread-17142.html) |
Get variable from class inside another class - hcne - Mar-30-2019 Hi everyone, I am building a code roughly organised as the example here: class parent: def __init__(self): self.variable_1 = 1 self.instance_child = [] class child: def __init(self): self.variable_2 = 0 def get_variable_1(self): self.variable_2 = 1 ### print(self.variable_1) def new_child(self): self.instance_child.append(self.child()) # -------------------- instance = parent() instance.new_child() instance.instance_child[0].get_variable_1()I have one class "parent" that contains another class "child", and instances are creates sequencially in the list "instance_child". What I am trying to do is to read variable_1 from inside the class 'child' without copying it. I could of course do " self.instance_child[0].variable_2 = self.variable_1 ", but I am trying to get a value from "parent" without repeating it in "child". Is there any solution to do so ? Thanks :) PS: I can also accept an alternative way of writting this code, as long as I can call multiple instances of 'child' into 'parent'. RE: Get variable from class inside another class - ichabod801 - Mar-30-2019 You could do this by having the child keep track of the parent: class parent: def __init__(self): self.variable_1 = 1 self.instance_child = [] class child: def __init(self, parent): self.parent = parent self.variable_2 = 0 def get_variable_1(self): self.variable_2 = 1 ### print(self.parent.variable_1) def new_child(self): self.instance_child.append(self.child(self)) # -------------------- instance = parent() instance.new_child() instance.instance_child[0].get_variable_1() RE: Get variable from class inside another class - hcne - Mar-30-2019 Simple and efficient, thanks a lot. One technical question if I may: Would you know whether all the information variable in 'parent' are repeated into 'child' in memory, or is it literally taking track of the content ? RE: Get variable from class inside another class - ichabod801 - Mar-30-2019 The information is not being repeated. The parent attribute of the child is just pointing to where the parent is stored in memory. |