0

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!

1
  • 2
    you want setattr(self, whatever), there is no self.globals(), not sure why you thought there was Commented Aug 25, 2020 at 8:51

3 Answers 3

1

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])
Sign up to request clarification or add additional context in comments.

Comments

0

Your problem is that you are trying to make a function call

self.globals()

You need to specify the function or change it into an attribute like that:

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

Like that you won't have the same error and will create a Dictionary.

Comments

0

Please try global instead of globals, It may work.

class test:


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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.