python3新特性函數注釋Function Annotations用法分析,python3annotations

來源:互聯網
上載者:User

python3新特性函數注釋Function Annotations用法分析,python3annotations

本文分析了python3新特性函數注釋Function Annotations用法。分享給大家供大家參考,具體如下:

Python 3.X新增加了一個特性(Feature),叫作函數注釋 Function Annotations

它的用途雖然不是文法層級的硬性要求,但是顧名思義,它可做為函數額外的注釋來用。

Python中普通的函數定義如下:

def func(a, b, c):  return a + b + c>>> func(1, 2, 3)6

添加了函數注釋的函數會變成如下形式:

def func(a: 'spam', b: (1, 10), c: float) -> int:  return a + b + c>>> func(1, 2, 3)6

注釋的一般規則是參數名後跟一個冒號(:),然後再跟一個expression,這個expression可以是任何形式。

傳回值的形式是 -> int,annotation可被儲存為函數的attributes。

查看所有的annotation,可通過如下語句:

>>> func.__annotations__{'c': <class 'float'>, 'a': 'spam', 'b': (1, 10), 'return': <class 'int'>}

如果為函數增加了注釋,可不可以繼續使用預設參數呢?答案是肯定的。

>>> def func(a: 'spam' = 4, b: (1, 10) = 5, c: float = 6) -> int:...  return a + b + c...>>> func(1, 2, 3)6>>> func()15>>> func(1, c=10)16>>> func.__annotations__{'c': <class 'float'>, 'a': 'spam', 'b': (1, 10), 'return': <class 'int'>}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.