0

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
1
  • 5
    This seems better suited for a dictionary. Why not set the values with your key being a string constructed like you posted above? my_dict["Segment"+segment_number.frequency] = 33 Commented Jun 15, 2015 at 17:28

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

-1

Not the most secure solution but you could use exec:

exec("Segment"+segment_number+".frequency=33")

3 Comments

It is better to forget that 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...
deets, do you have any links the legitimate uses? I'm intrigued, as a former toddler who no longer sees any use for the gattling gun.
@AlexanderHuszagh this is one I can remember: re-creating the signature of a decorated function so you get proper error-messages on them github.com/micheles/decorator/blob/master/src/decorator.py

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.