4
我寫一個函數與左邊的說法,只是類似像內置range
功能如何寫多個簽名提示在PyCharm與Python3
的問題是,如何編寫類型提示,可以顯示它應該被調用的兩種方式。
例如,當我在range
功能PyCharm鍵入命令+ P(CTRL + P)(範圍是在PY3的對象,但它是沒有問題的):
self:range, stop: int
-------------------------------------------------
self:range, start: int, stop: int, step: int=-1
但my_range
:
def my_range(start: int, stop: int = None, step: int=1):
"""
list_range(stop)
list_range(start, stop, step)
return list of integers from start (default 0) to stop,
incrementing by step (default 1).
"""
if stop is None:
start, stop = 0, start
return list(range(start, stop, step))
類型命令+ p後,我得到了:
start: int, stop: Optional[int], step: int=-1
有誰知道如何實現?非常感謝您的幫助!
也許嘗試尋找使用[重載](http://mypy.readthedocs.io/en/latest/function_overloading.html)? (函數重載是PEP 484的一部分,Pycharm正在理解/正在積極努力朝着遵從的方向發展。鏈接的文檔指出,mypy僅在存根中理解重載註釋,但是如果這是最新的/如果也是這種情況爲Pycharm)。 (如果你想查看'range'函數/對象具有的確切類型註釋,請參見[typeshed](https://github.com/python/typeshed/blob/master/stdlib/3/builtins.pyi#L717)) 。 – Michael0x2a
它的工作原理!非常感謝! – Garfield