Python — 反射性地初始化类



我正在用Python创建一个命令系统。我有一个模块vkcommands,它有一个处理来自聊天的命令的类(这是一个聊天机器人),在它里面,我还有具有nameusagemin_rank等属性的类VKCommand。然后我有模块vkcmds,其中包含实现这些命令的子模块:

...
vkcommands.py
vkcmds
|- __init__.py  # empty
|- add_group.py
|- another_cmd.py
|- ...

命令的实现(例如add_group) 看起来像这样:

import ranks
import vkcommands
from vkcommands import VKCommand

class AddGroup(VKCommand):
def __init__(self, kristy):
VKCommand.__init__(self, kristy,
label='create',
# ... (other attributes)
min_rank=ranks.Rank.USER)
def execute(self, chat, peer, sender, args=None, attachments=None):
# implementation (called from vkcommands.py)

当用户在聊天中发送消息时,命令管理器会分析该消息并查看已注册commands列表,以查看这是普通消息还是机器人命令。目前,我手动注册commands列表中的所有命令,如下所示:

class VKCommandsManager:
def __init__(self, kristy):
from vkcmds import (
add_group,
next_class
)
self.kristy = kristy
self.commands = (
add_group.AddGroup(kristy),
next_class.NextClass(kristy)
)

现在我希望所有命令都使用反射自动注册。在 Java 中,我会遍历命令包中的所有类,反射性地getConstructor每个类,调用它来检索VKCommand对象,并将其添加到命令列表中。

如何在 Python 中做到这一点?同样,我需要的是:

  1. 遍历模块(文件夹)vkcmds/中的所有子模块;
  2. 对于每个子模块,检查是否有一些类X扩展到内部VKCommand;
  3. 如果 (2)true,则使用一个参数调用该类的构造函数(保证所有命令的构造函数只有一个已知类型的参数(我的机器人的主类));
  4. 将 (3) 中构造的对象 (? extends VKCommand) 添加到commands列表中,以便稍后迭代。

使用此文件结构:

- Project
├─ commands
|   ├─ base.py
|   ├─ baz.py
|   └─ foo_bar.py
|
└─ main.py

以及commands目录文件中的以下内容:

  • base.py

    class VKCommand:
    """ We will inherit from this class if we want to include the class in commands.  """
    
  • baz.py

    from commands.base import VKCommand
    class Baz(VKCommand):
    pass
    
    def baz():
    """ Random function we do not want to retrieve.  
    
  • foo_bar.py

    from .base import VKCommand
    
    class Foo(VKCommand):
    """ We only want to retrieve this command.  """
    pass
    
    class Bar:
    """ We want to ignore this class.  """
    pass
    
    def fizz():
    """  Random function we do not want to retrieve. """
    

我们可以使用以下代码直接检索类实例和名称:

  • main.py

    """
    Dynamically load all commands located in submodules.
    This file is assumed to be at most 1 level higher than the
    specified folder.
    """
    import pyclbr
    import glob
    import os
    def filter_class(classes):
    inherit_from = 'VKCommand'
    classes = {name: info for name, info in classes.items() if inherit_from in info.super}
    return classes
    # Locate all submodules and classes that it contains without importing it.
    folder = 'commands'  # `vkcmds`.
    submodules = dict()
    absolute_search_path = os.path.join(os.path.dirname(__file__), folder, '*.py')
    for path in glob.glob(absolute_search_path):
    submodule_name = os.path.basename(path)[:-3]
    all_classes = pyclbr.readmodule(f"commands.{submodule_name}")
    command_classes = filter_class(all_classes)
    if command_classes:
    submodules[submodule_name] = command_classes
    # import the class and store an instance of the class into the command list
    class_instances = dict()
    for submodule_name, class_names in submodules.items():
    module = __import__(f"{folder}.{submodule_name}")
    submodule = getattr(module, submodule_name)
    for class_name in class_names:
    class_instance = getattr(submodule, class_name)
    class_instances[class_name] = class_instance
    print(class_instances)
    

解释

解决办法是双重的。它首先找到所有具有从VKCommand继承的类的子模块,并且位于文件夹"命令"中。这会导致以下输出包含必须分别导入和实例化的模块和类:

{'baz': {'Baz': <pyclbr.Class object at 0x000002BF886357F0>}, 'foo_bar': {'Foo': <pyclbr.Class object at 0x000002BF88660668>}}

代码的第二部分在运行时导入正确的模块和类名。变量class_instance包含类名和对可用于实例化的类的引用。最终输出将是:

{'Baz': <class 'commands.baz.Baz'>, 'Foo': <class 'commands.foo_bar.Foo'>}

重要提示:

  1. 该代码仅在导入更深 1 个字典的模块时有效。如果要递归使用它,则必须找到相对路径差,并使用正确的(完整)相对导入路径更新pyclbr.readmodule__import__

  2. 只有包含从VKCommand继承的类的模块才会被加载。所有其他模块都不会导入,必须手动导入。

我相信您可以制作文件夹中所有命令的数组,然后遍历它们并实例化对象。

__init__.py

all_commands = [AddGroup, AnotherCmd, ...]

像这样实例化它们:

objects = [Cmd(arg1, arg2, ...) for Cmd in all_commands]

编辑: 您还可以使用您所说的获取文件夹中所有类名的方法检索类名。

最新更新