Python Forum
Defining an object's argument whose name is stored in a variable - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Defining an object's argument whose name is stored in a variable (/thread-31438.html)



Defining an object's argument whose name is stored in a variable - arbiel - Dec-10-2020

Hi everybody

Window being a class, I define an Window objet's argument whose name is stored in a variable with the following code :
w=Window()
arg='toto'
val='any value'
exec('w.'+arg+'=val')
w.toto
'any value'
Generally speacking, using «exec» is not a very good practice.

Is there a smarter way to proceed ?

Arbiel


RE: Defining an object's argument whose name is stored in a variable - buran - Dec-10-2020

built-in setattr()

Quote:This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123.

setattr(w, 'toto', val)



RE: Defining an object's argument whose name is stored in a variable - arbiel - Dec-11-2020

(Dec-10-2020, 10:32 PM)buran Wrote: built-in setattr()

Quote:This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123.

setattr(w, 'toto', val)
Hi buran

Thanks a lot

Arbiel