0

I want to define new variables within a class method, but it just shows AttributeError: 'MyClass' object has no attribute 'var1':

class MyClass():

    def __init__(self, stuff):
        self.stuff = stuff
    
        for i in range(len(self.stuff)):
            locals()['var' + str(i)] = "e"
        
d = MyClass("hello")
print(d.var1)

And if I write it this way, it'll say name 'self' is not defined instead:

class MyClass():

    def __init__(self, stuff):
        self.stuff = stuff
    
    for i in range(len(self.stuff)):
        locals()['var' + str(i)] = "e"
        
d = MyClass("hello")
print(d.var1)

I know locals()['var' + str(i)] = "e" will work like this if I just use it outside a method, but I want my class to recieve data from the outside.

class MyClass():    
    for i in range(len("hello")):
        locals()['var' + str(i)] = "e"
        
d = MyClass()
print(d.var1)
S.B
  • 13,077
  • 10
  • 22
  • 49
hmm
  • 37
  • 3
  • 2
    Why not use list? Declaring variables like this is very bad method – cylee Jan 08 '22 at 07:23
  • Does this answer your question? [How do you create different variable names while in a loop?](https://stackoverflow.com/questions/6181935/how-do-you-create-different-variable-names-while-in-a-loop) – Gino Mempin Jan 08 '22 at 07:25

1 Answers1

0

Take a look at setattr(). Looks like you want to set custom attributes on your class instance. Why you might want to do that is a different topic.

class MyClass:

    def __init__(self, stuff):
        self.stuff = stuff

        for i, letter in enumerate(self.stuff):
            setattr(self, f"var{i}", letter)


d = MyClass("hello")
print(d.var0)
# Will print "h".
print(d.var1)
# Will print "e".
print(d.var2)
# Will print "l".
# etc.
S.B
  • 13,077
  • 10
  • 22
  • 49
Nikita
  • 6,101
  • 2
  • 26
  • 44