title: python get/set class variable inside class
body: <p>I do not know how to access a class object inside another class object. 
  Given a class "Best Result" which consists of </p>
  
  <ol>
  <li>an integer value </li>
  <li>an array of class "Color"</li>
  </ol>
  
  <p>As shown in the code below. My questions are:</p>
  
  <p>(A) In class "Best Result" def "SetColors", how to initialize self.colors to size of colors? The code below seems to assign empty list, so when I copy param "colors" to "self.colors" it said "index out of range". Also, is deepcopy the right way?</p>
  
  <pre><code>  self.colors = list(colors)
    for i in range(0, len(colors)):
      self.colors[i]= copy.deepcopy(colors[i])  
  </code></pre>
  
  <p>(B) How to set and get array of class "Color" inside class "Best Result"?</p>
  
  <hr>
  
  <p>Thanks for the comment, I tried to refine the code and got the answer for my questions below.</p>
  
  <hr>
  
  <pre><code>import copy
  
  class Color(object):
      __elems__ = "num", "nodelist"
  
      def __init__(self):
          self.num = 0                    
          self.nodelist = []              
  
      def items(self):
          return [
              (field_name, getattr(self, field_name)) 
               for field_name in self.__elems__]
  
  class BestResult(object):
      __elems__ = "objfunc", "colors"
  
      def __init__(self):
          self.objfunc = 0        
          self.colors = []              
  
      def setObjFunc(self, value):
          if value &lt; self.objfunc:
              self.objfunc = value
  
      def getObjFunc(self):
          return self.objfunc
  
      def setColors(self, colors):
          # Q1: How to initialize self.colors to size of colors? Index out of range now as self.colors has zero length.
          self.colors = list(colors)    
          for i in range(0, len(colors)):
              # Q2: Is this the right way to copy class?
              self.colors[i]= copy.deepcopy(colors[i])   
  
      def getColors(self):
          return self.colors
  
  def funcA():
  
      br = []
      br.append(BestResult())
  
      colors = []
      colors.append(Color())
      colors[0].num = 5
      colors[0].nodelist = [10, 20 , 30 , 40, 50]
  
      colors.append(Color())
      colors[1].num = 2
      colors[1].nodelist = [6, 7]
  
      br[0].setObjFunc(-100)
  
      # Q3: How to set colors[0] and colors[1] into br's colors?          
      br[0].setColors(colors)       
  
      print("br=%d" %br[0].getObjFunc())
      # Q4 How to retrieve each elements of (num &amp; nodelist) in br[0].colors
      res = br[0].getColors()
      print res[0].num
      print res[0].nodelist
      print res[1].num
      print res[1].nodelist   
  
  
  if __name__ == '__main__':
      funcA()
  </code></pre>