Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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!

like image 668
Nyambaa Avatar asked Aug 10 '10 17:08

Nyambaa


People also ask

How do you create an instance of a class dynamically in Python?

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.

How do you create an instance of a class in Python?

To create instances of a class, you call the class using class name and pass in whatever arguments its __init__ method accepts.

How do you create a dynamic object class?

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.

What is __ new __ in Python?

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.


3 Answers

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()
like image 61
elewinso Avatar answered Oct 08 '22 12:10

elewinso


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

like image 27
Scott Lance Avatar answered Oct 08 '22 10:10

Scott Lance


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)
like image 13
Tobias Ernst Avatar answered Oct 08 '22 11:10

Tobias Ernst