简体   繁体   English

从名称动态导入的类按名称导入模块:

[英]Dynamically import class by name from module imported as:

I have searched high and low and can't find a proper solution. 我搜索过高低,找不到合适的解决方案。

I need to dynamically create objects and store them in dictionaries using a for loop from a class that is in a different file. 我需要动态创建对象,并使用来自不同文件中类的for循环将它们存储在字典中。

To avoid name space pollution I like to import my modules like so: 为了避免名称空间污染,我喜欢这样导入我的模块:

from my_folder import my_file as mf

the loop looks like this: 循环看起来像这样:

self.my_dict = {} # create empty dictionary

    for F in ('One', 'Two', 'Three', ...):
        object = F(var1, var2)
        self.my_dict[F] = object

on the line object = F(var1, var2) I need the F be referring to mf.One , mf.Two and so on. 在行object = F(var1, var2)我需要F引用mf.Onemf.Two等。

How do I append the value F to mf so it reads it as mf.value-of-F instead of reading it as mf.F ? 如何将值F附加到mf以便将其读取为mf.value-of-F而不是将其读取为mf.F

I know I must be missing something very obvious, just not obvious to me right now. 我知道我一定会错过一些非常明显的东西,只是现在对我而言并不明显。 Thanks 谢谢

尝试使用以下语法:

object = mf.__dict__[F](var1, var2)

There are almost certainly better solutions to your problem, but your example is so short and contrived that it's hard to give good advice. 几乎可以肯定,您的问题有更好的解决方案,但是您的示例如此简短且人为设计,以至于很难给出好的建议。

To address the specific question you asked, you can use getattr to get a function or class from a module based on a string: 要解决您提出的特定问题,可以使用getattr从基于字符串的模块中获取函数或类:

for F in ('One', 'Two', 'Three', ...):
    Cls = getattr(mf, F)
    obj = Cls(var1, var2)
    self.my_dict[F] = obj

A simpler approach might be to iterate over the classes themselves: 一个更简单的方法可能是遍历这些类本身:

for F in (mf.One, mf.Two, mf.Three):
    obj = F(var1, var2)
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM