If you want to create multiple attributes of an object, you can use the built-in function setattr. There are three arguments: the object to which the attribute is added, the attribute name, and the value.
import numpy as np
class Test:
pass
test = Test()
for i in range(10):
setattr(test, 'var' + str(i), np.random.randint(10))
print(test.var5)
for name, value in test.__dict__.items():
print(f'{name} : {value}')
output
2
var0 : 2
var1 : 6
var2 : 2
var3 : 1
var4 : 2
var5 : 2
var6 : 7
var7 : 2
var8 : 7
var9 : 4
Recommended Posts