Python:如何使用 Importlib 创建 class 对象

Python: How to create a class object using Importlib

我知道类似的问题已经 asked/answered 好几次了。但请继续阅读..

我正在尝试根据 Python 3.6 中的“Convert string to Python Class Object”中所述的字符串值创建 Class。

utils.py

class Foo(object):
    def __init__(self):
        print("In the constructor of Foo")

    def What(self):
        print("so what ... ")

class FooParam(object):
    def __init__(self, v):
        self.value = v
        print("In the constructor of FooParam")

    def What(self):
        print("Value=" % self.value)
        print("So what now ...")

welcome.py

def TEST1():
    m = importlib.import_module("utils")
    c = getattr(m, "Foo")
    c.What()  

if __name__ == '__main__': 
    TEST1()

错误

TypeError: What() missing 1 required positional argument: 'self'

那我做错了什么?

另外,如何创建 "FooParam" 的对象并将值传递给构造函数。

导入模块后,只需使用存储导入模块的变量进行访问:

m = importlib.import_module("utils")
foo = m.Foo()
foo.What()

import_module 执行与 import.

相同的步骤

c = getattr(m, "Foo") 行代码等效于 f = Foo,这意味着您不是在创建实例,而是获取对 class.

的引用

我怀疑 c 是 class Foo 而不是 class.

的实例

这相当于简单地调用

Foo.what()

这就是为什么没有定义 self 的原因!

而你想要的是创建一个 class 的实例(给它一个 'self' 属性),然后调用它的方法,即

foo_instance = Foo()
foo_instance.What()

所以尝试将 c.What() 替换为..

foo_instance = c()
foo_instance.What()

对于 FooParam:

#import the class FooParam
c = getattr(m, "FooParam")
#create an instance of the class, initializing its values (and self)
fooparam_instance = c(3.14)
#call its method!
fooparam_instance.What()

总的来说,我会将变量 c 分别重命名为 foo_import 和 fooparam_import :)