相关疑难解决方法(0)

返回基类的子类实例的工厂方法的Python 3类型提示

假设我有两个类,Base并且在中Child有一个工厂方法Base。factory方法调用另一个类方法,该类方法可以被Base的子类覆盖。

class Base(object):
    @classmethod
    def create(cls, *args: Tuple) -> 'Base':
        value = cls._prepare(*args)
        return cls(value)

    @classmethod
    def _prepare(cls, *args: Tuple) -> Any:
        return args[0] if args else None

    def __init__(self, value: Any) -> None:
        self.value = value


class Child(Base):
    @classmethod
    def _prepare(cls, *args: Tuple) -> Any:
        return args[1] if len(args) > 1 else None

    def method_not_present_on_base(self) -> None:
        pass
Run Code Online (Sandbox Code Playgroud)

有没有一种注释的方法,Base.create以便静态类型检查器可以推断Base.create()返回的实例BaseChild.create()返回的实例Child,以便下面的示例通过静态分析?

base = …
Run Code Online (Sandbox Code Playgroud)

python type-hinting python-3.x

9
推荐指数
2
解决办法
2118
查看次数

标签 统计

python ×1

python-3.x ×1

type-hinting ×1