Python Forum

Full Version: Defining an object's argument whose name is stored in a variable
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
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)
(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