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 845 May-02-2021, 03:45 PM
Last Post: Anldra12
  [solved] Variable number of dictionnaries as argument in def() paul18fr 11 1,274 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 874 Apr-09-2020, 08:48 AM
Last Post: DeaD_EyE
  SyntaxError: positional argument follows keyword argument syd_jat 3 3,000 Mar-03-2020, 08:34 AM
Last Post: buran
  How to pass variable as an argument to be used in a function? t4keheart 8 1,413 Jan-16-2020, 01:37 PM
Last Post: buran
  Problem defining a variable rix 6 1,083 Dec-17-2019, 11:34 AM
Last Post: rix
  zip file variable prints <zipfile.ZipFile object at 0x7f83fd13bd90> ? Rsh 9 1,562 Jun-27-2019, 02:00 PM
Last Post: Rsh
  Add a stored procedure with variable using MySQL Connector UtiliseIT 0 1,124 May-04-2019, 12:46 PM
Last Post: UtiliseIT
  How are these Employee objects stored? Vysero 2 1,377 Jul-13-2018, 12:05 PM
Last Post: buran
  How to call the stored values Dieselkaine 6 1,821 Jul-04-2018, 10:35 PM
Last Post: gontajones

Forum Jump:

User Panel Messages

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