【发布时间】:2021-03-27 16:13:50
【问题描述】:
目前我正在将文件提取到操作系统的临时目录。其中一个文件是一个 Python 文件,其中包含一个我需要处理的类。 Python 的文件是已知的,但文件中的类的名称是未知的。但可以安全地假设,只有一个类,并且该类是另一个类的子类。
我尝试使用importlib,但我无法掌握课程。
到目前为止我试过了:
# Assume
# module_name contains the name of the class and -> "MyClass"
# path_module contains the path to the python file -> "../Module.py"
spec = spec_from_file_location(module_name, path_module)
module = module_from_spec(spec)
for pair in inspect.getmembers(module):
print(f"{pair[1]} is class: {inspect.isclass(pair[1])}")
当我遍历模块的成员时,它们都没有被打印为一个类。
在这种情况下,我的班级称为BasicModel,控制台上的输出如下所示:
BasicModel is class: False
解决这个问题的正确方法是什么?
编辑:
由于请求了文件的内容,请执行以下操作:
class BasicModel(Sequential):
def __init__(self, class_count: int, input_shape: tuple):
Sequential.__init__(self)
self.add(Input(shape=input_shape))
self.add(Flatten())
self.add(Dense(128, activation=nn.relu))
self.add(Dense(128, activation=nn.relu))
self.add(Dense(class_count, activation=nn.softmax))
【问题讨论】:
-
可以分享一下文件的内容,我们可以试验一下吗?
-
我添加了文件的内容
标签: python-3.x python-importlib