简体   繁体   English

来自父类的提示

[英]Type hint from parent class

How can you hint a class from the parent class like this? 您如何像这样从父类提示一个类?

class Cls1:
    class Cls2:
        p2: int

    class Cls3:
        p3: Cls2  # undefined name 'Cls2'

    class Cls4:
        p4: Cls2  # undefined name 'Cls2'

Yes, see PEP 484 §Forward References : 是的,请参阅PEP 484§转发参考

When a type hint contains names that have not been defined yet, that definition may be expressed as a string literal, to be resolved later. 当类型提示包含尚未定义的名称时,该定义可以表示为字符串文字,稍后再解析。

A situation where this occurs commonly is the definition of a container class, where the class being defined occurs in the signature of some of the methods. 通常会发生这种情况的情况是容器类的定义,其中定义的类出现在某些方法的签名中。

So, in your example, reference the not-yet-defined type in a string: 因此,在您的示例中,在字符串中引用尚未定义的类型:

class Cls1:
    class Cls2:
        p2: int

    class Cls3:
        p3: 'Cls2'

    class Cls4:
        p4: 'Cls2'

Note that, while Python is happy to accept the above, mypy (v0.641), seems to have a bug and can't find Cls2 . 请注意,尽管Python很乐意接受上述内容,但mypy(v0.641)似乎有一个错误,无法找到Cls2

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

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