繁体   English   中英

Type-Hinting Child class 返回自我

[英]Type-Hinting Child class returning self

有什么方法可以键入抽象父 class 方法,以便知道子 class 方法返回自身,而不是抽象父方法。

class Parent(ABC):
    @abstractmethod
    def method(self) -> [what to hint here]:
        pass

class Child1(Parent)
    def method(self):
        pass

    def other_method(self):
        pass

class GrandChild1(Child1)
    def other_method_2(self):
        pass

这更多是为了改进 PyCharm 或 VScode 的 python 插件等 IDE 的自动完成功能。

因此, 这里的文档中描述了一般方法

import typing
from abc import ABC, abstractmethod

T = typing.TypeVar('T', bound='Parent') # use string

class Parent(ABC):
    @abstractmethod
    def method(self: T) -> T:
        ...

class Child1(Parent):
    def method(self: T) -> T:
        return self

    def other_method(self):
        pass

class GrandChild1(Child1):
    def other_method_2(self):
        pass

reveal_type(Child1().method())
reveal_type(GrandChild1().method())

mypy给了我们:

test_typing.py:22: note: Revealed type is 'test_typing.Child1*'
test_typing.py:23: note: Revealed type is 'test_typing.GrandChild1*'

请注意,我必须继续使用类型变量才能使其正常工作,所以当我最初尝试在子 class 注释中使用实际的子 class 时,它(错误地?)继承了孙子中的类型:

class Child1(Parent):
    def method(self) -> Child1:
        return self

我会用mypy:

test_typing.py:22: note: Revealed type is 'test_typing.Child1'
test_typing.py:23: note: Revealed type is 'test_typing.Child1'

同样,我不确定这是否是预期/正确的行为。 mypy 文档当前有一个警告:

此功能是实验性的。 使用自我 arguments 的类型注释检查代码仍未完全实现。 Mypy 可能不允许有效代码或允许不安全代码。

Python 3.11引入了基于PEP-0673的更优雅的解决方案,预定义类型Self官方文档)。 例子:

from typing import Self

class Parent(ABC):
    @abstractmethod
    def method(self) -> Self:
        pass

class Child1(Parent)
    def method(self) -> Self:
        pass

    def other_method(self) -> Self:
        pass

class GrandChild1(Child1)
    def other_method_2(self) -> Self:
        pass

它也涵盖类方法

class Shape:
    @classmethod
    def from_config(cls, config: dict[str, float]) -> Self:
        return cls(config["scale"])

注意:对于 pre-python-3.11,可以使用:

1 - 引用类型,例如

class Parent:
    def method(self) -> "Parent":
        pass

2 - 或推迟类型提示评估( PEP-0563 ,或其他SO 答案,python 3.7+):

from __future__ import annotations
class Parent:
    def method(self) -> Parent:
        pass

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM