最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解python3類型注釋annotations實(shí)用案例

 更新時(shí)間:2021年01月20日 09:31:57   作者:Sunny_Future  
這篇文章主要介紹了詳解python3類型注釋annotations實(shí)用案例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

1、類型注解簡介

Python是一種動態(tài)類型化的語言,不會強(qiáng)制使用類型提示,但為了更明確形參類型,自python3.5開始,PEP484為python引入了類型注解(type hints)

示例如下:

在這里插入圖片描述 

2、常見的數(shù)據(jù)類型

  • int,long,float: 整型,長整形,浮點(diǎn)型
  • bool,str: 布爾型,字符串類型
  • List, Tuple, Dict, Set: 列表,元組,字典, 集合
  • Iterable,Iterator: 可迭代類型,迭代器類型
  • Generator:生成器類型
  • Sequence: 序列

3、基本的類型指定

def test(a: int, b: str) -> str:
  print(a, b)
  return 200


if __name__ == '__main__':
  test('test', 'abc')

函數(shù)test,a:int 指定了輸入?yún)?shù)a為int類型,b:str b為str類型,-> str 返回值為srt類型??梢钥吹?,在方法中,我們最終返回了一個(gè)int,此時(shí)pycharm就會有警告;

當(dāng)調(diào)用這個(gè)方法時(shí),參數(shù)a 輸入的是字符串,此時(shí)也會有警告;

but…,pycharm這玩意兒 只是提出了警告,但實(shí)際上運(yùn)行是不會報(bào)錯(cuò),畢竟python的本質(zhì)還是動態(tài)語言。

在這里插入圖片描述

4、復(fù)雜的類型指定

指定列表

from typing import List
Vector = List[float]


def scale(scalar: float, vector: Vector) -> Vector:
  return [scalar * num for num in vector]


# type checks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
print(new_vector)

指定 字典、元組 類型

from typing import Dict, Tuple, Sequence

ConnectionOptions = Dict[str, str]
Address = Tuple[str, int]
Server = Tuple[Address, ConnectionOptions]


def broadcast_message(message: str, servers: Sequence[Server]) -> None:
  print(message)
  print(servers)

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.


if __name__ == '__main__':
  broadcast_message('OK', [(('127.0.0.1', 8080), {"method": "GET"})])

在這里插入圖片描述

這里需要注意,元組這個(gè)類型是比較特殊的,因?yàn)樗遣豢勺兊摹?br /> 所以,當(dāng)我們指定Tuple[str, str]時(shí),就只能傳入長度為2,并且元組中的所有元素都是str類型

5、創(chuàng)建變量時(shí)的類型指定

對于常量或者變量添加注釋

from typing import NamedTuple


class Employee(NamedTuple):
  name: str
  id: int = 3


employee = Employee('Guido')
# assert employee.id == 3  # 當(dāng)類型一致時(shí),不會輸出內(nèi)容,反之報(bào)錯(cuò)
assert employee.id == '3'  # 當(dāng)類型一致時(shí),不會輸出內(nèi)容,反之報(bào)錯(cuò)
# AssertionError

指定一個(gè)變量odd,顯式的聲明了它應(yīng)該是整數(shù)列表。如果使用mypy來執(zhí)行這個(gè)腳本,將不會收到任何提示輸出,因?yàn)橐呀?jīng)正確地傳遞了期望的參數(shù)去執(zhí)行所有操作。

from typing import List

def odd_numbers(numbers: List) -> List:
  odd: List[int] = []
  for number in numbers:
    if number % 2:
      odd.append(number)

  return odd

if __name__ == '__main__':
  numbers = list(range(10))
  print(odd_numbers(numbers))

mypy 安裝

pip install mypy

執(zhí)行 mypy file,正常情況下不會報(bào)錯(cuò)

C:\Users\Sunny_Future\AppData\Roaming\Python\Python36\Scripts\mypy.exe tests.py

# 指定 環(huán)境變量或者 linux 下可以直接執(zhí)行 mypy
# mypy tests.py

Success: no issues found in 1 source file

在這里插入圖片描述

接下來,嘗試更改一下代碼,試圖去添加整形之外的其他類型內(nèi)容!那么執(zhí)行則會檢查報(bào)錯(cuò)

from typing import List


def odd_numbers(numbers: List) -> List:
  odd: List[int] = []
  for number in numbers:
    if number % 2:
      odd.append(number)

  odd.append('foo')

  return odd


if __name__ == '__main__':
  numbers = list(range(10))
  print(odd_numbers(numbers))

代碼中添加一個(gè)行新代碼,將一個(gè)字符串foo附加到整數(shù)列表中。現(xiàn)在,如果我們針對這個(gè)版本的代碼來運(yùn)行mypy

C:\Users\Sunny_Future\AppData\Roaming\Python\Python36\Scripts\mypy.exe tests.py

在這里插入圖片描述

tests.py:114: error: Argument 1 to “append” of “l(fā)ist” has incompatible type “str”; expected “int”
Found 1 error in 1 file (checked 1 source file)

6、 泛型指定

from typing import Sequence, TypeVar, Union

T = TypeVar('T')   # Declare type variable


def first(l: Sequence[T]) -> T:  # Generic function
  return l[0]


T = TypeVar('T')       # Can be anything
A = TypeVar('A', str, bytes) # Must be str or bytes
A = Union[str, None]     # Must be str or None

7、再次重申

在Python 3.5中,你需要做變量聲明,但是必須將聲明放在注釋中:

# Python 3.6
odd: List[int] = []

# Python 3.5
odd = [] # type: List[int]

如果使用Python 3.5的變量注釋語法,mypy仍將正確標(biāo)記該錯(cuò)誤。你必須在 #井號之后指定type:。如果你刪除它,那么它就不再是變量注釋了?;旧螾EP 526增加的所有內(nèi)容都為了使語言更加統(tǒng)一。

8、不足之處

雖然指定了 List[int] 即由 int 組成的列表,但是,實(shí)際中,只要這個(gè)列表中存在 int(其他的可以為任何類型),pycharm就不會出現(xiàn)警告,使用 mypy 才能檢測出警告!

from typing import List


def test(b: List[int]) -> str:
  print(b)
  return 'test'


if __name__ == '__main__':
  test([1, 'a'])

pycharm 并沒有檢測出類型錯(cuò)誤,沒有告警

在這里插入圖片描述mypy

工具 檢測到 類型異常,并進(jìn)行了報(bào)錯(cuò)

在這里插入圖片描述 

9、demo

# py2 引用
from__future__import annotations
class Starship:
  captain: str = 'Picard'
  damage: int
  stats: ClassVar[Dict[str, int]] = {}

  def __init__(self, damage: int, captain: str = None):
    self.damage = damage
    if captain:
      self.captain = captain # Else keep the default

  def hit(self):
    Starship.stats['hits'] = Starship.stats.get('hits', 0) + 1

enterprise_d = Starship(3000)
enterprise_d.stats = {} # Flagged as error by a type checker
Starship.stats = {} # This is OK
from typing import Dict
class Player:
  ...
players: Dict[str, Player]
__points: int

print(__annotations__)
# prints: {'players': typing.Dict[str, __main__.Player],
#     '_Player__points': <class 'int'>}
class C:
  __annotations__ = 42
  x: int = 5 # raises TypeError

到此這篇關(guān)于詳解python3類型注釋annotations實(shí)用案例的文章就介紹到這了,更多相關(guān)python3類型注釋annotations內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • python中正則表達(dá)式 re.findall 用法

    python中正則表達(dá)式 re.findall 用法

    在python中,通過內(nèi)嵌集成re模塊,程序媛們可以直接調(diào)用來實(shí)現(xiàn)正則匹配。本文重點(diǎn)給大家介紹python中正則表達(dá)式 re.findall 用法,感興趣的朋友跟隨小編一起看看吧
    2018-10-10
  • Python實(shí)現(xiàn)鼠標(biāo)自動在屏幕上隨機(jī)移動功能

    Python實(shí)現(xiàn)鼠標(biāo)自動在屏幕上隨機(jī)移動功能

    這篇文章主要介紹了Python實(shí)現(xiàn)鼠標(biāo)自動在屏幕上隨機(jī)移動功能,具有很好的參考價(jià)值,希望對大家有所幫助。還等什么?一起跟隨小編過來看看吧
    2020-03-03
  • Python+matplotlib實(shí)現(xiàn)堆疊圖的繪制

    Python+matplotlib實(shí)現(xiàn)堆疊圖的繪制

    Matplotlib作為Python的2D繪圖庫,它以各種硬拷貝格式和跨平臺的交互式環(huán)境生成出版質(zhì)量級別的圖形。本文將利用Matplotlib庫繪制堆疊圖,感興趣的可以了解一下
    2022-03-03
  • python 實(shí)現(xiàn)Requests發(fā)送帶cookies的請求

    python 實(shí)現(xiàn)Requests發(fā)送帶cookies的請求

    這篇文章主要介紹了python 實(shí)現(xiàn)Requests發(fā)送帶cookies請求的方法,幫助大家更好的理解和使用python,感興趣的朋友可以了解下
    2021-02-02
  • python三大器之迭代器、生成器、裝飾器

    python三大器之迭代器、生成器、裝飾器

    迭代是Python最強(qiáng)大的功能之一,是訪問集合元素的一種方式;迭代器是一個(gè)可以記住遍歷的位置的對象,本文給大家介紹python三大器之迭代器、生成器、裝飾器的相關(guān)知識,感興趣的朋友跟隨小編一起看看吧
    2022-01-01
  • python安裝與使用redis的方法

    python安裝與使用redis的方法

    這篇文章主要介紹了python安裝與使用redis的方法,分析了安裝與配置的具體步驟,并結(jié)合實(shí)例詳細(xì)分析了redis數(shù)據(jù)庫的具體使用技巧,需要的朋友可以參考下
    2016-04-04
  • jupyter notebook指定啟動目錄的方法

    jupyter notebook指定啟動目錄的方法

    這篇文章主要介紹了jupyter notebook指定啟動目錄的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-03-03
  • django中F與Q查詢的使用

    django中F與Q查詢的使用

    一般查詢都是單條件查詢,F(xiàn)和Q是組合條件查詢,本文主要介紹了django中F與Q查詢的使用,感興趣的可以了解一下
    2021-06-06
  • python 利用百度API進(jìn)行淘寶評論關(guān)鍵詞提取

    python 利用百度API進(jìn)行淘寶評論關(guān)鍵詞提取

    這篇文章主要介紹了python 利用百度API進(jìn)行淘寶評論關(guān)鍵詞提取,幫助大家更好的理解和學(xué)習(xí)使用python,感興趣的朋友可以了解下
    2021-03-03
  • python內(nèi)置堆的具體實(shí)現(xiàn)

    python內(nèi)置堆的具體實(shí)現(xiàn)

    本文主要介紹了python內(nèi)置堆的具體實(shí)現(xiàn),堆的表示方法,從上到下,從左到右存儲,與列表十分相似,本文就來介紹一下,感興趣的可以了解一下
    2023-03-03

最新評論

辽宁省| 贵定县| 廉江市| 惠水县| 南京市| 崇明县| 宝清县| 通州市| 修武县| 山阳县| 南和县| 呼玛县| 休宁县| 尼玛县| 延长县| 和硕县| 额尔古纳市| 涪陵区| 湟源县| 三都| 司法| 耿马| 正定县| 陵川县| 甘德县| 嵩明县| 章丘市| 疏勒县| 新乡县| 镇原县| 蒲城县| 洛宁县| 龙井市| 盐边县| 西贡区| 浦县| 荆州市| 宽甸| 揭阳市| 华容县| 偏关县|