简体   繁体   English

如何从自我生成返回类型提示?

[英]How to generate a return type-hint from self?

I'd like to generate the return type hint from a string which is defined on __init__() within the class:我想从 class 中的__init__()上定义的字符串生成返回类型提示:

class MyItem:
    return_type: str = None

    def __init__(self, return_type: str):
        self.return_type = return_type

    def get_item() -> self.return_type:   # <--- Is something like that possible?
        return ...
    

Any idea how to achieve that?知道如何实现吗?

No. I don't think so.不,我不这么认为。 Type hints are used by type checkers, IDEs, linters, etc... .类型检查器、IDE、linter 等使用类型提示。 Because your classes aren't instantiated until runtime, this won't work.因为您的类直到运行时才被实例化,所以这是行不通的。

Consider the following code:考虑以下代码:

class MyItem:
    return_type: str = None

    def __init__(self, return_type: str):
        self.return_type = return_type

    def get_item() -> self.return_type:   # <--- Is something like that possible?
        return ...

a = MyItem("Str")
b = a 
b.return_type = "int" 

The linter would have to run the constructor for a , note that b is a , and then update the return type where b 's return type is updated. linter 必须运行a的构造函数,注意ba ,然后更新b的返回类型更新的返回类型。 I can't see a way for the linter or IDE to check return types without running the code first, and we know that type hints have no effect at runtime.我看不到 linter 或 IDE 在不先运行代码的情况下检查返回类型的方法,而且我们知道类型提示在运行时无效。 This is a cool idea though.不过,这是一个很酷的主意。 This type of behaviour reminds me of sealed classes in kotlin.这种行为让我想起了 kotlin 中的密封类。

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

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