[英]Instantiate class dynamically with locate
I am trying to instantiate a class dynamically from a string that is fed to a method.我正在尝试从提供给方法的字符串动态实例化一个类。
from pydoc import locate
name = "folder.subfolder.classname"
my_class = locate(name)
instance = my_class()
Doing this results in an error:这样做会导致错误:
TypeError: 'module' object is not callable
My question is: how can I dinamically know which class I need to call?我的问题是:我如何动态地知道我需要调用哪个类? If I hardcode the value and do
my_class.classname()
I can instantiate it, but I want that last part to be dynamic, instead of hardcoded.如果我对值进行硬编码并执行
my_class.classname()
我可以实例化它,但我希望最后一部分是动态的,而不是硬编码。 How can I do that?我怎样才能做到这一点?
Edit 2:编辑2:
This solution will gather all classes available in the module the user provides, and then simply instantiates the first class.该解决方案将收集用户提供的模块中所有可用的类,然后简单地实例化第一个类。
import inspect
from pydoc import locate
name = "folder.subfolder.classname"
my_module = locate(name)
all_classes = inspect.getmembers(my_module, inspect.isclass)
if len(all_classes) > 0:
instance = all_classes[0][1]()
Edit:编辑:
Gathered from the comments I believe the following code will work for your use case:从评论中收集到的我相信以下代码适用于您的用例:
from pydoc import locate
name = "folder.subfolder.classname"
my_module = locate(name)
class_name = name.rsplit('.')[-1]
my_class = getattr(my_module, class_name)
instance = my_class()
You do seem to be a bit confused as to what modules are which resulted in our miscommunication.您似乎对哪些模块导致了我们的误会感到有些困惑。 class.py doesn't point to a class, but to a module.
class.py 不指向类,而是指向模块。 In that module (your class.py file) there can be multiple classes.
在该模块(您的 class.py 文件)中可以有多个类。 For the answer above I just assume that in your class.py file you have a class with the same name as the file.
对于上面的答案,我只是假设在您的 class.py 文件中,您有一个与该文件同名的类。
Original Answer:原答案:
Well as your error shows, your my_class
variable is actually a module object.正如您的错误所示,您的
my_class
变量实际上是一个模块对象。 The name you provide doesn't actually point to your class but to the module containing the class.您提供的名称实际上并不指向您的类,而是指向包含该类的模块。
To get a class from a module object by string you can do:要通过字符串从模块对象中获取类,您可以执行以下操作:
my_class = getattr(module, class_name)
and then like in your example code you can instantiate it like this:然后就像在您的示例代码中一样,您可以像这样实例化它:
instance = my_class()
To bring it all together:把它们放在一起:
module_name = "folder.subfolder.module_name"
my_module = locate(module_name)
my_class = getattr(my_module, class_name)
instance = my_class()
You didn't locate the class inside of the file:您没有在文件中找到该类:
from pydoc import locate
name = "folder.subfolder.filename.classname"
my_class = locate(name)
instance = my_class()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.