Python Forum
Defining an object's argument whose name is stored in a variable
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Defining an object's argument whose name is stored in a variable
#1
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
Reply
#2
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)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
(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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  TypeError: int() argument must be a string, a bytes-like object or a number, not 'Non Anldra12 2 5,190 May-02-2021, 03:45 PM
Last Post: Anldra12
  [solved] Variable number of dictionnaries as argument in def() paul18fr 11 6,111 Apr-20-2021, 11:15 AM
Last Post: paul18fr
  When Defining a Function with an Equation as a Default Argument, which Value Is Used? OJGeorge4 4 2,653 Apr-09-2020, 08:48 AM
Last Post: DeaD_EyE
  SyntaxError: positional argument follows keyword argument syd_jat 3 5,820 Mar-03-2020, 08:34 AM
Last Post: buran
  How to pass variable as an argument to be used in a function? t4keheart 8 3,580 Jan-16-2020, 01:37 PM
Last Post: buran
  Problem defining a variable rix 6 3,185 Dec-17-2019, 11:34 AM
Last Post: rix
  zip file variable prints <zipfile.ZipFile object at 0x7f83fd13bd90> ? Rsh 9 4,107 Jun-27-2019, 02:00 PM
Last Post: Rsh
  Add a stored procedure with variable using MySQL Connector UtiliseIT 0 2,289 May-04-2019, 12:46 PM
Last Post: UtiliseIT
  While loop variable defining Yordy 5 3,982 Jan-04-2018, 04:53 PM
Last Post: buran
  User defined method as variable or argument AeranicusCascadia 5 4,268 Dec-13-2017, 04:47 PM
Last Post: AeranicusCascadia

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020