S
S
Stefan Blackwall2021-07-01 23:10:56
Python
Stefan Blackwall, 2021-07-01 23:10:56

How to add a new variable with a custom name to an object?

Not needed yet, but very interesting... Let's say I want to add to

class Test:
   def __init__(self):
      self.sma=None
t=Test()

new variables are allowed in an exaggeratedly similar way
for i in range(0,3):
    exec('t.sma_'+str(i)+'=None')

and in the end I want to get
print(t.sma_0) // None
print(t.sma_1) // None
print(t.sma_2) // None
print(t.sma_3) // None

How is this done correctly? And how often is this generally used?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
galaxy, 2021-07-02
@redburnz

What exactly bothers you?
New attributes can be added to the object in an obvious way: If the attribute name is non-constant - setattr() :
t.sma_1 = 17

setattr(t, "sma_" + str(2), 17)
# можно и так
t.__setattr__("sma_" + str(2), 17)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question