Search code examples
pythonfunctionclassinstance-variables

Class instance variable assigned inside function


Can a class instance variable be set equal to a class instance variable of another class that was created inside a function? The code below seems to work (a.var = [5, []]) after the call to func() but I want to make sure that I am not missing anything:

def func():
  class C:
    def __init__(self):
      self.var = [[] for _ in np.arange(2)]
  c = C()
  c.var[0] = 5
  a.var = c.var

class A:
  def __init__(self):
    self.id = 0
    self.var = [[] for _ in np.arange(2)]

if __name__ == "__main__":
  a = A()
  func()

Solution

  • Yes, you're just assigning objects. Now, you should be very careful with the way you've written this. It's a bad idea to rely on the scope you have set out -- it will work, but I could easily see someone losing track of "a" and it never getting passed down to func(). A better implementation of func, in my opinion:

    def func(a, val=5):
      class C:
        def __init__(self):
          self.var = [[] for _ in range(2)]
      c = C()
      c.var[0] = val
      a.var = c.var
    
    class A:
      def __init__(self):
        self.id = 0
        self.var = [[] for _ in range(2)]
    
    if __name__ == "__main__":
      a = A()
      func(a)
      aa = A()
      func(aa, val=10)
    

    Since lists can contain any objects, you could do some even weirder stuff like.

    aa.var[1] = a