2

I have been looking for this for quite sometime and also looked at previously asked questions like:

how to dynamically create an instance of a class in python?

Does python have an equivalent to Java Class.forName()?

Can you use a string to instantiate a class in python?

And also many more, in some of them they are importing the class or using the name of the class somehow in definition.

Edit:

I need to take a list as input and create classes with strings in the list as their name.

store_list = {'store1', 'storeabc', 'store234'}

Now i can do,

store1 = type(store_list[0], (models.Model,), attrs)
storeabc = type(store_list[1], (models.Model,), attrs)
store234 = type(store_list[2], (models.Model), attrs)

But i still have to use the names of the class in some way in the code, i have no way of knowing what the list will be, and i want the classes to be created with name taken from the list.

Community
  • 1
  • 1
Osiris92
  • 181
  • 8
  • 2
    Do you want to create an object from a class or do you want to create the class itself dynamically? If the later have you looked at [this question](http://stackoverflow.com/questions/10555844/dynamically-creating-a-class-from-file-in-python)? – syntonym Jul 05 '16 at 09:38
  • 2
    We need [MCVE] - sample input and expected output. – Łukasz Rogalski Jul 05 '16 at 09:39
  • Added a bit more information about what i want to do. – Osiris92 Jul 05 '16 at 10:11
  • *“But i still have to use the names of the class in some way in the code”* – for example..? – poke Jul 05 '16 at 10:12
  • How can you "use the names of the class ... in the code" when you have "no way of knowing what the names will be" ? – donkopotamus Jul 05 '16 at 10:17
  • Yes exactly i can't use the name of the class, for example to create a class using type i still have to use the name of the class, which is what most people have suggested in other answers. I want a way to create the class without using the name of the class in the code. I want the name to be the string taken from the list. – Osiris92 Jul 05 '16 at 10:51
  • I still don’t know what you would need the class name inside the code for. Please show an actual example. – poke Jul 05 '16 at 10:56

1 Answers1

2

You could store the classes you're dynamically creating into a dictionary, mapping class names to classes. This way you can use such a dictionary to access your classes by name later in your code, e.g. to create instances. For example:

store_list = {'store1', 'storeabc', 'store234'}
name2class = {}
for name in store_list:
    name2class[name] = type(name, (models.Model,), attrs)
. . .
my_instance = name2class[name](...)
davidedb
  • 867
  • 5
  • 12