How to dynamically compose and access class attributes in Python? -


I have a Python class on which there are properties named: date1, date2, date3, etc.

Runtime, I have a variable I, which is an integer

What do I want to do? For example,

if I == 1, I want to use myobject.date1

If I == 2, I want to use myobject.date2

And I want to do something for the class instead of the feature.

For example, I have a bunch of squares: MyClass1, MyClass2, MyClass3, etc. And I have a variable k

If k == 1, I want to instantify a new one

If k == 2, I want to instal a new example of MyClass2

How can I do this?

Edit

I am hoping to avoid using the other-if-else statement to select the appropriate attributes / classes .

Is there a way to create a class in Python using the value of a variable using the name on the fly?

you getattr () Do not know the name runtime:

  obj = Myobject () I = 7 date7 = getattr (obj, 'date% d'% i) like the # obj.date7  < / Pre> 

If you keep numbered classes in your coded module, then Foo , you can use getattr () to reach them by number. .

  foo.py class: 1 class passed pass 2: pass [etc.] bar.py: import foo i = 3 someClass = getattr (foo, "square% d"% i) # some Also as a class = foo.Class3 obj = someClass () # someClass foo.Class3 # is an indicator for the lower version: Obj = getattr (foo, "class% d"% i) ()  

After saying all this, you should avoid actually this way because you will never be able to know that these numbers of properties and sections are used to read through your entire codebase Apart from being done. You are better by putting everything in the dictionary.


Comments