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.

7
  • 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? Commented Jul 5, 2016 at 9:38
  • 2
    We need minimal reproducible example - sample input and expected output. Commented Jul 5, 2016 at 9:39
  • Added a bit more information about what i want to do. Commented Jul 5, 2016 at 10:11
  • “But i still have to use the names of the class in some way in the code” – for example..? Commented Jul 5, 2016 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" ? Commented Jul 5, 2016 at 10:17

1 Answer 1

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](...)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.