[英]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.