Python Forum

Full Version: Get variable from class inside another class
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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'.
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()
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 ?
The information is not being repeated. The parent attribute of the child is just pointing to where the parent is stored in memory.