假設一個函式接受一個物件作為引數。可以有多種方式來表達引數物件的創建,其中一些方式具有表現力,并且可能更易于使用。
舉一個簡單的例子,我們有一個函式,它接受DateTime. 如果可能,我們還希望接受 DateTime 的字串表示形式(例如'20220606')。
# version 1, strict. must send a DateTime
def UsefulFunc(startdate: DateTime) -> None:
pass
# version 2, allow more types, but loose on type hints
def UsefulFunc(startdate: (DateTime, str)) -> None:
# check if type is str, convert to DateTime if yes
pass
# version 3, multiple signatures to accept and call the base function
def UsefulFuncString(startdatestr: str) -> None:
# convert startdatestr to DateTime
UsefulFunc(startdate)
# … …
Python推薦什么方法(我來自C#背景)?如果沒有明確的指示/或根據情況決定,有什么考慮?
uj5u.com熱心網友回復:
如果你想輸入提示你的函式,你可以使用typing.Union
from datetime import datetime
from typing import Union
def UsefulFunc(startdate:Union[str, datetime]) -> None
...
或在 py3.10
def UsefulFunc(startdate:str|datetime) -> None
...
但是型別提示只是 python 中的裝飾,如果你想根據這些型別做一些事情,你需要檢查你的函式內部并相應地作業
def UsefulFunc(startdate:str|datetime) -> None
if isinstance(startdate,str):
...
elif isinstance(startdate,datetime):
...
else:
raise ValueError("Invalid type")
還有functools.singledispatch可以幫助您為您完成上述操作
from functools import singledispatch
@singledispatch
def UsefulFunc(startdate):
... #else case
@UsefulFunc.register
def _(startdate:datetime):
... #datetime case
@UsefulFunc.register
def _(startdate:str):
... #str case
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/487539.html
上一篇:帶引數的bash函式
