How to dynamically compose and access class attributes in Python?

Viewed 20568

I have a Python class that have attributes named: date1, date2, date3, etc.

During runtime, I have a variable i, which is an integer.

What I want to do is to access the appropriate date attribute in run time based on the value of i.

For example,

if i == 1, I want to access myobject.date1

if i == 2, I want to access myobject.date2

And I want to do something similar for class instead of attribute.

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

if k == 1, I want to instantiate a new instance of MyClass1

if k == 2, I want to instantiate a new instance of MyClass2

How can i do that?

EDIT

I'm hoping to avoid using a giant if-then-else statement to select the appropriate attribute/class.

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

5 Answers

to get a list of all the attributes, try:

dir(<class instance>)
Related