[英]How to generate a return type-hint from self?
我想从 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 ...
知道如何实现吗?
不,我不这么认为。 类型检查器、IDE、linter 等使用类型提示。 因为您的类直到运行时才被实例化,所以这是行不通的。
考虑以下代码:
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"
linter 必须运行a
的构造函数,注意b
是a
,然后更新b
的返回类型更新的返回类型。 我看不到 linter 或 IDE 在不先运行代码的情况下检查返回类型的方法,而且我们知道类型提示在运行时无效。 不过,这是一个很酷的主意。 这种行为让我想起了 kotlin 中的密封类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.