Python:如何使用Importlib创建类对象
我知道类似的问题已经被问过/回答过好几次了。但是请继续读下去 我正试图从一个字符串值创建一个类,如Python 3.6中的“”所述 utils.pyPython:如何使用Importlib创建类对象,python,python-importlib,Python,Python Importlib,我知道类似的问题已经被问过/回答过好几次了。但是请继续读下去 我正试图从一个字符串值创建一个类,如Python 3.6中的“”所述 utils.py class Foo(object): def __init__(self): print("In the constructor of Foo") def What(self): print("so what ... ") class FooParam(object): def __ini
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 ...")
def TEST1():
m = importlib.import_module("utils")
c = getattr(m, "Foo")
c.What()
if __name__ == '__main__':
TEST1()
欢迎光临。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 ...")
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\u模块执行与import
相同的步骤
这c=getattr(m,“Foo”)
行代码相当于f=Foo
,因此这意味着您不是在创建实例,而是在获取对该类的引用。我怀疑c是类Foo,而不是该类的实例
这相当于简单地调用
Foo.what()
这就是为什么自我没有定义
而您想要的是创建类的实例(给它一个“self”属性),然后调用它的方法,即
foo_instance = Foo()
foo_instance.What()
所以试着用..替换c.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:)“如何创建一个“fooparam”对象并将值传递给构造函数。”->您可以使用参数调用它的构造函数<代码>FooParam=getattr(m,“FooParam”);obj=FooParam(无论什么)
。谢谢你们的回答。错过了重要的一点是令人尴尬的。现在可以了。