当前我正在将文件提取到操作系统的临时目录中。其中一个文件是一个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
,控制台上的Output看起来像这样:
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))
使用dir()
获取文件的属性,使用inspect
检查属性是否为类。如果是,则可以创建一个对象。
假设你的文件路径是/tmp/mysterious
,你可以这样做:
import importlib
import inspect
from pathlib import Path
import sys
path_pyfile = Path('/tmp/mysterious.py')
sys.path.append(str(path_pyfile.parent))
mysterious = importlib.import_module(path_pyfile.stem)
for name_local in dir(mysterious):
if inspect.isclass(getattr(mysterious, name_local)):
print(f'{name_local} is a class')
MysteriousClass = getattr(mysterious, name_local)
mysterious_object = MysteriousClass()