简体   繁体   English

如何键入带有封闭 class 类型的方法并使用 inheritance 更新该方法?

[英]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().fooB().foo时, Self被自动推断为具体的 class AB 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.

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