导入一个pythonclass的非打包模块
Import a python class of non packaged module
在 /absolute/path/file.py
中给定一个 .py 文件,其中包含 class MyClass
未打包 [即不能使用 import_module(x.y.z)],
如何从 Python3.X 中的另一个 .py 文件动态导入 class?重要的是它是动态完成的,因为 class 要导入的名称和路径会根据某些参数而有所不同。
您可以使用 importlib
导入您的模块,并使用 inspect
在导入的模块中按名称查找 class
import importlib.util
import inspect
absolute_path = '/absolute/path/file.py'
file_name = 'file.py'
class_name = 'Class'
spec = importlib.util.spec_from_file_location(file_name, absolute_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
cls = None
for member in inspect.getmembers(module):
if member[0] == class_name:
cls = member[1]
instance = cls()
print(instance)
# <file.py.Class object at 0x7f3e002c0000>
在 /absolute/path/file.py
中给定一个 .py 文件,其中包含 class MyClass
未打包 [即不能使用 import_module(x.y.z)],
如何从 Python3.X 中的另一个 .py 文件动态导入 class?重要的是它是动态完成的,因为 class 要导入的名称和路径会根据某些参数而有所不同。
您可以使用 importlib
导入您的模块,并使用 inspect
在导入的模块中按名称查找 class
import importlib.util
import inspect
absolute_path = '/absolute/path/file.py'
file_name = 'file.py'
class_name = 'Class'
spec = importlib.util.spec_from_file_location(file_name, absolute_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
cls = None
for member in inspect.getmembers(module):
if member[0] == class_name:
cls = member[1]
instance = cls()
print(instance)
# <file.py.Class object at 0x7f3e002c0000>