I have list of class names and want to create their instances dynamically. for example:
names=[
'foo.baa.a',
'foo.daa.c',
'foo.AA',
....
]
def save(cName, argument):
aa = create_instance(cName) # how to do it?
aa.save(argument)
save(random_from(names), arg)
How to dynamically create that instances in Python? thanks!
Python Code can be dynamically imported and classes can be dynamically created at run-time. Classes can be dynamically created using the type() function in Python. The type() function is used to return the type of the object. The above syntax returns the type of object.
To create instances of a class, you call the class using class name and pass in whatever arguments its __init__ method accepts.
In C++, the objects can be created at run-time. C++ supports two operators new and delete to perform memory allocation and de-allocation. These types of objects are called dynamic objects. The new operator is used to create objects dynamically and the delete operator is used to delete objects dynamically.
The __new__() is a static method of the object class. It has the following signature: object.__new__(class, *args, **kwargs) Code language: Python (python) The first argument of the __new__ method is the class of the new object that you want to create.
Assuming you have already imported the relevant classes using something like
from [app].models import *
all you will need to do is
klass = globals()["class_name"]
instance = klass()
This is often referred to as reflection or sometimes introspection. Check out a similar questions that have an answer for what you are trying to do:
Does Python Have An Equivalent to Java Class forname
Can You Use a String to Instantiate a Class in Python
This worked for me:
from importlib import import_module
class_str: str = 'A.B.YourClass'
try:
module_path, class_name = class_str.rsplit('.', 1)
module = import_module(module_path)
return getattr(module, class_name)
except (ImportError, AttributeError) as e:
raise ImportError(class_str)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With