[英]How do I type hint a method with the type of the enclosing class and update that with inheritance?
Similar but different to How do I type hint a method with the type of the enclosing class?与How do I type hint a method with the type of the enclosure class? 类似但不同? .
.
How can I set something on the parent class so that a type hint gets updated through inheritance?如何在父 class 上设置某些内容,以便通过 inheritance 更新类型提示?
class A:
# Make some change here
def foo(self, bar: 'A'):
pass
class B(A):
# Get the hinting of the code below, but without writing it for every inheritor.
# def foo(self, bar: 'B'):
# pass
pass
Parameterise over the type of self
, which is always an instance of "the current class":参数化
self
的类型,它始终是“当前类”的一个实例:
from typing import TypeVar
Self = TypeVar('Self')
class A:
# `bar` must be of the same type as the current instance `self`
def foo(self: Self, bar: Self):
pass
class B(A):
pass
When calling A().foo
or B().foo
, Self
is automatically inferred to the concrete class A
or B
, respectively.当调用
A().foo
或B().foo
时, Self
被自动推断为具体的 class A
或B
。 This then automatically constraints the other parameter to match the inferred TypeVar and thus the class.然后,这会自动约束其他参数以匹配推断的 TypeVar,从而匹配 class。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.