I created a class called SignalParam in python containing different properties (frequency, voltage, time, etc)
I would like to create many instances of this type
vars()['Segment'+str(segment_number)] = SignalParam()
this line is working and i can create variables "Segment1", "Segment2", ....
My question is: i would like to call those variabes like
"Segment"+segment_number.freqency=33
3 Answers 3
This is bad style. Use a dictionary instead, and simple keys to access:
d = {}
d['Segment'+str(segment_number)] = SignalParam()
d['Segment'+str(segment_number)].frequency = 33
The reason you shouldn't use vars is because it means you create global variables, which you should avoid. And given your access-style, you don't even need it.
Comments
It's probably better to use a dictionary here. Define one with segments = {}. Then you can create a SignalParam by keying into your dictionary with your segment number:
segments[segment_number] = SignalParam()
and use the object like this:
segments[segment_number].frequency = 33
Comments
Not the most secure solution but you could use exec:
exec("Segment"+segment_number+".frequency=33")
3 Comments
exec exists. In my +15 years of python, I found maybe 2.3 legit uses deep in meta-programming. It's like giving a toddler a gatling gun. No idea what it does, but it's funny revolving...
my_dict["Segment"+segment_number.frequency] = 33