诀窍是注释明确添加到cls
参数,结合TypeVar
,为generics,并且Type
,以represent a class rather then the instance itself,像这样:
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
(和self
)未加注释,但如果您需要参考特定的子类,则可以添加一个explicit annotation。请注意,此功能仍处于试验阶段,在某些情况下可能会出现问题。您可能还需要使用从Github克隆的mypy的最新版本,而不是pypi上可用的 - 我不记得该版本是否支持classmethods的此功能。
' - >'Foo''是正确的,这就是所有你可以(或应该)执行的返回值。 – jonrsharpe