in

(Python) Is there a way to create new variables that works inside a method?


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)



Source: https://stackoverflow.com/questions/70630348/python-is-there-a-way-to-create-new-variables-that-works-inside-a-method

a distributed, scalable load-testing tool built in go that leverages Google Cloud Functions

Facebook Launches ‘Privacy Center’ to Educate Users on Data Collection and Privacy Options