python _init_函数中令人困惑的属性分配

时间:2018-12-07 13:42:39

标签: python

以下代码段来自SQLAlchemy source code

class EngineStrategy(object):
    """An adaptor that processes input arguments and produces an Engine.
    Provides a ``create`` method that receives input arguments and
    produces an instance of base.Engine or a subclass.
    """

    def __init__(self):
        strategies[self.name] = self

最后一条语句如何工作?

1 个答案:

答案 0 :(得分:3)

EngineStrategy是一种抽象类。如果尝试搜索此类的用法,则只会从该类中找到继承。

所以self.name实际上来自cls.name(类变量),就像下面的PlainEngineStrategy一样:

class PlainEngineStrategy(DefaultEngineStrategy):
    """Strategy for configuring a regular Engine."""

    name = 'plain'
    engine_cls = base.Engine

这允许将所有策略存储在strategies字典中,其结构为:{'stategy_name': strategy_class}

sqlalchemy注释有关:官方回购的镜像现在位于https://github.com/sqlalchemy/sqlalchemy