Search code examples
pythonloopsclassglobal-variables

Python - Cannot make global variable become a attribute in a class


I want to make a class which generate new variable every loop and save it into the object, yet python shows error:

class test:
  def __init__(self, bn = [1,2,3], fl = [1,2,3]):
    for i in range(1,len(bn)):
      self.globals()['fl_%s' % i] = fl[i-1]

model = test(bn = [1,2,3], fl = [1,2,3])
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-49-22b3186d8727> in <module>()
----> 1 model = test(bn = [1,2,3], fl = [1,2,3])

<ipython-input-48-7c8e68e85b8c> in __init__(self, bn, fl)
      2   def __init__(self, bn = [1,2,3], fl = [1,2,3]):
      3     for i in range(1,len(bn)):
----> 4       self.globals()['fl_%s' % i] = fl[i-1]

AttributeError: 'test' object has no attribute 'globals'

I want to have something like model.fl_1 but it seems something wrong with how I use the globals() function and I don't know how to solve this...

Or is there another way to do what I want? Many thanks!


Solution

  • If you want to programatically set attributes on a class from a string, then you need setattr():

    class test:
      def __init__(self, bn=[1, 2, 3], fl=[1, 2, 3]):
        for i in range(1, len(bn)):
          setattr(self, 'fl_%s' % i, fl[i - 1])