I have a class with dynamic variable i want to make them as attribute of my class
class test:
def __init__(self):
for i in range(10):
globals()["var" str(i)]=i
I tried this method but it doesn't work
class test:
def __init__(self):
for i in range(10):
globals()["self.var" str(i)]=i
CodePudding user response:
class test:
def __init__(self):
for i in range(10):
setattr(test, "var" str(i), i)
x = test()
CodePudding user response:
Much like imerla said, but slightly different:
class test:
def __init__(self):
for i in range(10):
self.__setattr__(f"var{i}", i)