从不同目录实例化 Python 个子类
Instantiate Python subclasses from different directories
我有一些模块位于不同的目录中。仅当 类 是 ParentClass
的子 类 时,我如何才能在这些 module
中实例化 类?本质上,我正在尝试下面这样的事情,想知道如何实现 child_class_name
from importlib.machinery import SourceFileLoader
from parent_class import ParentClass
instances = []
script_path1 = r'/some/different/directory/some_child.py'
script_path2 = r'/some/different/directory/another_child.py'
for script_path in [script_path1, script_path2]:
module = SourceFileLoader('module', script_path).load_module()
child_class_name = "If a class in this module is a subclass of ParentClass"
ChildClass = getattr(module, child_class_name)
instances.append(ChildClass())
这应该适用于这个理解列表:
childclasses = [obj for obj in vars(module).values()
if isinstance(obj,type) and issubclass(obj,ParentClass)]
vars(module).values()
returns 模块中的所有对象。
然后你可以用issubclass(obj,ParentClass)
过滤子classes。
(isinstance
只会帮助过滤 class 个对象。)
childclasses
是一个 class 的列表,您可以直接实例化,而无需使用 getattr
:
for ChildClass in childclasses:
instances.append(ChildClass())
编辑 :
为避免 ParentClass
,您可以将列表转换为集合,如果存在则将其删除:
childclasses = set([obj for obj in vars(module).values()
if isinstance(obj,type) and issubclass(obj,ParentClass)])
if ParentClass in childclasses:
childclasses.remove(ParentClass)
或在理解中添加另一个测试:
childclasses = [obj for obj in vars(module).values()
if isinstance(obj,type) and
issubclass(obj,ParentClass)and
obj is not ParentClass ]
我有一些模块位于不同的目录中。仅当 类 是 ParentClass
的子 类 时,我如何才能在这些 module
中实例化 类?本质上,我正在尝试下面这样的事情,想知道如何实现 child_class_name
from importlib.machinery import SourceFileLoader
from parent_class import ParentClass
instances = []
script_path1 = r'/some/different/directory/some_child.py'
script_path2 = r'/some/different/directory/another_child.py'
for script_path in [script_path1, script_path2]:
module = SourceFileLoader('module', script_path).load_module()
child_class_name = "If a class in this module is a subclass of ParentClass"
ChildClass = getattr(module, child_class_name)
instances.append(ChildClass())
这应该适用于这个理解列表:
childclasses = [obj for obj in vars(module).values()
if isinstance(obj,type) and issubclass(obj,ParentClass)]
vars(module).values()
returns 模块中的所有对象。
然后你可以用issubclass(obj,ParentClass)
过滤子classes。
(isinstance
只会帮助过滤 class 个对象。)
childclasses
是一个 class 的列表,您可以直接实例化,而无需使用 getattr
:
for ChildClass in childclasses:
instances.append(ChildClass())
编辑 :
为避免 ParentClass
,您可以将列表转换为集合,如果存在则将其删除:
childclasses = set([obj for obj in vars(module).values()
if isinstance(obj,type) and issubclass(obj,ParentClass)])
if ParentClass in childclasses:
childclasses.remove(ParentClass)
或在理解中添加另一个测试:
childclasses = [obj for obj in vars(module).values()
if isinstance(obj,type) and
issubclass(obj,ParentClass)and
obj is not ParentClass ]