Python - 函式註解



函式註解

Python函式註解 功能使您能夠新增有關在函式定義中宣告的引數以及返回值型別的其他解釋性元資料。 Python 直譯器 在執行 函式 時不會考慮它們。它們主要用於 Python IDE,以便為程式設計師提供詳細的文件。

儘管您可以使用 Python 的 文件字串 功能來記錄函式,但如果對函式的原型進行了某些更改,它可能會過時。因此,註解功能是在 PEP 3107 的結果下引入 Python 的。

註解是新增到引數或返回值型別中的任何有效的 Python 表示式。註解的最簡單示例是規定引數的資料型別。註解是在引數前面放置一個冒號後作為表示式提到的。

示例

請記住,Python 是一種動態型別語言,並且在執行時不強制執行任何型別檢查。因此,使用 資料型別 對引數進行註解在呼叫函式時沒有任何效果。即使給出了非整數引數,Python 也不會檢測到任何錯誤。

def myfunction(a: int, b: int):
   c = a+b
   return c
   
print (myfunction(10,20))
print (myfunction("Hello ", "Python"))

它將產生以下輸出 -

30
Hello Python

帶返回值的函式註解

註解在執行時會被忽略,但對 IDE 和靜態型別檢查器庫(如 mypy)很有用。

您也可以為返回值型別提供註解。在括號之後和冒號符號之前,放置一個箭頭(->),後跟註解。

示例

在此示例中,我們為返回值型別提供了註解。

def myfunction(a: int, b: int) -> int:
   c = a+b
   return c
print(myfunction(56,88))
print(myfunction.__annotations__)

這將生成以下輸出 -

144
{'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}

帶表示式的函式註解

由於在執行時會忽略使用資料型別作為註解,因此您可以放置任何用作引數元資料的表示式。因此,函式可以具有任何任意表達式作為註解。

示例

在下面的示例中,我們使用表示式作為函式註解。

def total(x : 'marks in Physics', y: 'marks in chemistry'):
   return x+y
print(total(86, 88))
print(total.__annotations__)

以下是輸出 -

174
{'x': 'marks in Physics', 'y': 'marks in chemistry'}

帶預設引數的函式註解

如果要同時指定預設引數和註解,需要將它放在註解表示式之後。預設引數必須位於引數列表中必需引數之後。

示例 1

以下示例演示瞭如何為函式的預設引數提供註解。

def myfunction(a: "physics", b:"Maths" = 20) -> int:
   c = a+b
   return c
print (myfunction(10))

Python 中的函式也是一個物件,並且它的一個屬性是 __annotations__。您可以使用 dir() 函式進行檢查。

print (dir(myfunction))

這將列印 myfunction 物件的列表,其中包含 __annotations__ 作為其中一個屬性。

['__annotations__', '__builtins__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__getstate__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

示例 2

__annotations__ 屬性本身是一個字典,其中引數是鍵,註解是其值。

def myfunction(a: "physics", b:"Maths" = 20) -> int:
   c = a+b
   return c
print (myfunction.__annotations__)

它將產生以下輸出 -

{'a': 'physics', 'b': 'Maths', 'return': <class 'int'>}

示例 3

函式可以具有任意位置和/或任意關鍵字引數。也可以為它們提供註解。

def myfunction(*args: "arbitrary args", **kwargs: "arbitrary keyword args") -> int:
   pass
print (myfunction.__annotations__)

它將產生以下輸出 -

{'args': 'arbitrary args', 'kwargs': 'arbitrary keyword args', 'return': <class 'int'>}

示例 4

如果您需要為函式引數提供多個註解表示式,請以字典物件的形式將其放在引數本身之前。

def division(num: dict(type=float, msg='numerator'), den: dict(type=float, msg='denominator')) -> float:
   return num/den
print (division.__annotations__)

它將產生以下輸出 -

{'num': {'type': <class 'float'>, 'msg': 'numerator'}, 'den': {'type': <class 'float'>, 'msg': 'denominator'}, 'return': <class 'float'>}
廣告