久久久精品一区ed2k-女人被男人叉到高潮的视频-中文字幕乱码一区久久麻豆樱花-俄罗斯熟妇真实视频

annotations怎么在python3中使用-創(chuàng)新互聯(lián)

這篇文章將為大家詳細(xì)講解有關(guān)annotations怎么在python3中使用,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。

創(chuàng)新互聯(lián)為您提適合企業(yè)的網(wǎng)站設(shè)計(jì)?讓您的網(wǎng)站在搜索引擎具有高度排名,讓您的網(wǎng)站具備超強(qiáng)的網(wǎng)絡(luò)競(jìng)爭(zhēng)力!結(jié)合企業(yè)自身,進(jìn)行網(wǎng)站設(shè)計(jì)及把握,最后結(jié)合企業(yè)文化和具體宗旨等,才能創(chuàng)作出一份性化解決方案。從網(wǎng)站策劃到成都網(wǎng)站設(shè)計(jì)、網(wǎng)站建設(shè), 我們的網(wǎng)頁(yè)設(shè)計(jì)師為您提供的解決方案。

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

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

示例如下:


annotations怎么在python3中使用

2、常見的數(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ǔ)言。


annotations怎么在python3中使用

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"})])

annotations怎么在python3中使用


這里需要注意,元組這個(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

annotations怎么在python3中使用

接下來(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

annotations怎么在python3中使用

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:。如果你刪除它,那么它就不再是變量注釋了。基本上PEP 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)有告警


annotations怎么在python3中使用mypy

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


annotations怎么在python3中使用

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)于annotations怎么在python3中使用就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

網(wǎng)頁(yè)標(biāo)題:annotations怎么在python3中使用-創(chuàng)新互聯(lián)
URL分享:http://sd-ha.com/article8/ihcip.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供虛擬主機(jī)、外貿(mào)建站關(guān)鍵詞優(yōu)化、網(wǎng)站建設(shè)、品牌網(wǎng)站設(shè)計(jì)、響應(yīng)式網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

成都網(wǎng)頁(yè)設(shè)計(jì)公司