1

I'm working on a program that needs to handle sets of a bunch of associated variables. I want to bundle them all into a class so I can access them intuitively...

class transition():
...

t1 = transition(stuff_to_initialize)
retrieve_that_variable = t1.that_variable_in_initialized_stuff 

but I'd like to be able to declare my instance variables from a for loop:

class transition(object):
    ''' instance of a transition includes...
    '''
    # order convention for uncertainty terms Cij
    __order = {'c11': 1, 'c22': 2, 'c33': 3, 'c12': 4, 'c13': 5, 'c23': 6}
    __vector = {'Rx': 0.0, 'Ry': 0.0, 'Rz': 0.0}


    def __init__(self, cij=__order, vector=__vector):
        # Things that a transition instance must specify
        self.layer_type = 0

        for item in cij.keys():
            self.item = 0           
        for item in vector.keys():
            self.item = 0

but in this example, after initializing an instance of transition I just have an instance variable transition.item.

Can I initialize instance variables from a list of variable names?

2
  • 1
    If I understand you, you want to name these things dynamically? Why not just create a variable that holds a copy of the dictionaries you're using for reference? Commented Oct 9, 2015 at 20:38
  • If I understood you correctly, this is a bad idea. Commented Oct 9, 2015 at 20:41

1 Answer 1

1

It's a bad way to go about it but the function you want is setattr. You can do

for item in cij.keys():
    setattr(self, item, 0)

So yes, you can initialize instance variables from a list of names. It's hard to see why you wouldn't just use a dictionary in this case though.

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

2 Comments

In my case I'm essentially replacing a human with a code to handle I/O for another simple program. At a later point I need to generate input files for a subprocess in a specific format , and in my mind being able to grab the relevant info from t1 = transition() ... t1.value_I_need makes the program less dependent on syntax... user input doesn't need specific keywords for parsing input, only for the class to be properly initialized. On the other hand, I'm self taught so I could be doing things in a silly way. Thanks for the response!
How is that different from t1 = {}... t1['value_I_need']? At some point in your programme the names of the attributes will have to be inputted and it's very hard to see why you wouldn't just store them as keys in a dictionary which maps them to the corresponding values.

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.