[英]how to dynamically create an instance of a class in python?
我有類名列表並希望動態創建它們的實例。 例如:
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)
如何在 Python 中動態創建該實例? 謝謝!
假設您已經使用類似的方法導入了相關類
from [app].models import *
你需要做的就是
klass = globals()["class_name"]
instance = klass()
這通常被稱為反思,有時也稱為自省。 查看一個類似的問題,這些問題對您正在嘗試做的事情有答案:
這對我有用:
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)
您通常可以完全避免字符串處理部分。
import foo.baa
import foo.AA
import foo
classes = [ foo.baa.a, foo.daa.c, foo.AA ]
def save(theClass, argument):
aa = theClass()
aa.save(argument)
save(random.choice(classes), arg)
請注意,我們不使用類名稱的字符串表示形式。
在 Python 中,您可以只使用類本身。
您可以使用 python 內置eval()
語句來實例化您的類。 像這樣:
aa = eval(cName)()
注意!
使用 eval 是危險的,並且是基於代碼注入的許多安全風險的關鍵。
我的問題是我想將參數傳遞給__init__
,參數是在命令行上的字符串中指定的。 例如,相當於
import a.b.ClassB as ClassB
instance = ClassB.ClassB('World')
命令行上的字符串是"abClassB.ClassB('World')"
使用模塊 abClassB 中的以下類
class ClassB():
def __init__(self, name:str):
self._name = name
def hello(self):
print("Hello " + self._name + "!")
我們可以使用以下內容創建這個類
import importlib
def create_instance(class_str:str):
"""
Create a class instance from a full path to a class constructor
:param class_str: module name plus '.' plus class name and optional parens with arguments for the class's
__init__() method. For example, "a.b.ClassB.ClassB('World')"
:return: an instance of the class specified.
"""
try:
if "(" in class_str:
full_class_name, args = class_name = class_str.rsplit('(', 1)
args = '(' + args
else:
full_class_name = class_str
args = ()
# Get the class object
module_path, _, class_name = full_class_name.rpartition('.')
mod = importlib.import_module(module_path)
klazz = getattr(mod, class_name)
# Alias the the class so its constructor can be called, see the following link.
# See https://www.programiz.com/python-programming/methods/built-in/eval
alias = class_name + "Alias"
instance = eval(alias + args, { alias: klazz})
return instance
except (ImportError, AttributeError) as e:
raise ImportError(class_str)
if __name__ == "__main__":
instance = create_instance("a.b.ClassB.ClassB('World')")
instance.hello()
我發現的最佳答案:更好的方法是制作字典:objects ={} Names =[object1,object2, object3]
對於名稱中的 objname:objects[objname]=classname()
發現於: https : //www.thecodingforums.com/threads/create-object-name-from-string-value.712461/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.