Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutate Variables with String Names (Python) [duplicate]

Tags:

python

If I have Bag(a=1,b=2,c=3) and I want to change the individual values. I can call self.a = 10 so my updated output would be: Bag(a=10,b=2,c=3).

If k = a and I have the code:

temp = ("self." + str(k))
print(temp) --> self.a

How can I do something like:

temp = 10

So it updates the bag (not temp itself to 10)?

Thanks

like image 674
MTG Avatar asked Feb 01 '26 04:02

MTG


1 Answers

Sounds like you're looking for setattr:

setattr(self, k, 10)
like image 129
wim Avatar answered Feb 02 '26 19:02

wim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!