返回实例的类方法的类型注释

2024-06-11

我应该如何注释@classmethod返回一个实例cls?这是一个不好的例子:

class Foo(object):
    def __init__(self, bar: str):
        self.bar = bar

    @classmethod
    def with_stuff_appended(cls, bar: str) -> ???:
        return cls(bar + "stuff")

这会返回一个Foo但更准确地返回哪个子类Foo这是被调用的,所以注释为-> "Foo"还不够好。


诀窍是显式添加注释cls参数,结合TypeVar, for generics http://mypy.readthedocs.io/en/stable/generics.html, and Type, to 代表一个类而不是实例本身 http://mypy.readthedocs.io/en/stable/kinds_of_types.html#the-type-of-class-objects,像这样:

from typing import TypeVar, Type

# Create a generic variable that can be 'Parent', or any subclass.
T = TypeVar('T', bound='Parent')

class Parent:
    def __init__(self, bar: str) -> None:
        self.bar = bar

    @classmethod
    def with_stuff_appended(cls: Type[T], bar: str) -> T:
        # We annotate 'cls' with a typevar so that we can
        # type our return type more precisely
        return cls(bar + "stuff")

class Child(Parent):
    # If you're going to redefine __init__, make sure it
    # has a signature that's compatible with the Parent's __init__,
    # since mypy currently doesn't check for that.

    def child_only(self) -> int:
        return 3

# Mypy correctly infers that p is of type 'Parent',
# and c is of type 'Child'.
p = Parent.with_stuff_appended("10")
c = Child.with_stuff_appended("20")

# We can verify this ourself by using the special 'reveal_type'
# function. Be sure to delete these lines before running your
# code -- this function is something only mypy understands
# (it's meant to help with debugging your types).
reveal_type(p)  # Revealed type is 'test.Parent*'
reveal_type(c)  # Revealed type is 'test.Child*'

# So, these all typecheck
print(p.bar)
print(c.bar)
print(c.child_only())

一般情况下,你可以离开cls (and self) 未注释,但如果需要引用具体子类,可以添加显式注释 http://mypy.readthedocs.io/en/stable/generics.html#generic-methods-and-generic-self。请注意,此功能仍处于实验阶段,在某些情况下可能会出现错误。您可能还需要使用从 Github 克隆的最新版本的 mypy,而不是 pypi 上可用的版本——我不记得该版本是否支持类方法的此功能。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

返回实例的类方法的类型注释 的相关文章

随机推荐