让子类使用子类

Have a subclass use a subclass

我开发了一个通用的 Environment class,它在 generic.py 文件中使用通用的 Agent class。 现在我想创建一个 SpecificEnvironment,它在 specific.py 文件中使用 SpecificAgent

到目前为止,我必须使用以下内容指定(具体)Environment

from generic import Environment

class SpecificEnvironment(Environment):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

如何让 SpecificEnvironment 使用 SpecificAgent subclass,而不是 Agent

请随意推荐一些读物,以便我自学。 我对面向对象编程比较陌生。

您可以有一个 class 属性来指示要使用哪个 Agent subclass。

class Environment:
    EnvironmentAgent = Agent

    ...

然后您需要将 Environment 中出现的每个 Agent 替换为 class 方法中的 self.EnvironmentAgentcls.EnvironmentAgent。这样,如果您的 subclass 提供了不同的 EnvironmentAgent 属性,它将被使用。

class SpecificEnvironment(Environment):
    EnvironmentAgent = SpecificAgent

    ...