在Python中使用动态导入有什么意义



让我们假设有一堆类,根据传入的参数,需要检测该类并调用其句柄方法。

可能的类别


class A:
def handle(self):
print('handle method of A class is invoking')
class B:
def handle(self):
print('handle method of B class is invoking')
class C:
def handle(self):
print('handle method of C class is invoking')
class D:
def handle(self):
print('handle method of D class is invoking')
class E:
def handle(self):
print('handle method of E class is invoking')

那么,你建议像下面这样映射类吗?

class_mapping = {
'a': A,
'b': B,
'c': C,
'd': D,
'e': E,
}
class Handler:
def __init__(self, param):
klass = class_mapping[param]
instance = klass()
instance.handle()

或者映射类路径并动态导入?为什么?

class_path_mapping = {
'a': "folder_name.A",
'b': "folder_name.B",
'c': "folder_name.C",
'd': "folder_name.D",
'e': "folder_name.E",
}
class DynamicImportHandler:
def __init__(self, param):
klass = importlib.import_module(class_path_mapping[param])
instance = klass()
instance.handle()

我建议遵循通常的规则:

  1. 如果预先知道要加载的python模块集,请导入它们。一个写得好的模块在导入时不应该有任何副作用,包括CPU或I/O负载过大。换句话说,进口应该是一种廉价的操作。

  2. 对于要加载的模块事先未知的情况,如插件系统,请保留动态加载。

如果您认为您的案例不符合一般规则,请提供更多信息。

class_mappingdict的第一种情况是:

handler = class_mapping[param] # create an instance

然后:

handler.handle() # invoke the method

最新更新