欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

1、類型注解簡(jiǎn)介

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

示例如下:

在這里插入圖片描述 

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

  • int,long,float: 整型,長(zhǎng)整形,浮點(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就會(huì)有警告;

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

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

在這里插入圖片描述

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í),就只能傳入長(zhǎng)度為2,并且元組中的所有元素都是str類型

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

對(duì)于常量或者變量添加注釋

from typing import NamedTuple


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


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

指定一個(gè)變量odd,顯式的聲明了它應(yīng)該是整數(shù)列表。如果使用mypy來(lái)執(zhí)行這個(gè)腳本,將不會(huì)收到任何提示輸出,因?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,正常情況下不會(huì)報(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

在這里插入圖片描述

接下來(lái),嘗試更改一下代碼,試圖去添加整形之外的其他類型內(nèi)容!那么執(zhí)行則會(huì)檢查報(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)在,如果我們針對(duì)這個(gè)版本的代碼來(lái)運(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的變量注釋語(yǔ)法,mypy仍將正確標(biāo)記該錯(cuò)誤。你必須在 #井號(hào)之后指定type:。如果你刪除它,那么它就不再是變量注釋了?;旧螾EP 526增加的所有內(nèi)容都為了使語(yǔ)言更加統(tǒng)一。

8、不足之處

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

from typing import List


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


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

pycharm 并沒(méi)有檢測(cè)出類型錯(cuò)誤,沒(méi)有告警

在這里插入圖片描述mypy

工具 檢測(cè)到 類型異常,并進(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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論