<center id="siaos"><meter id="siaos"></meter></center>
<strike id="siaos"></strike>

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

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

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

1、類型注解簡介

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

示例如下:


annotations怎么在python3中使用

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

  • int,long,float: 整型,長整形,浮點型

  • 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類型??梢钥吹剑诜椒ㄖ?,我們最終返回了一個int,此時pycharm就會有警告;

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

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


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中使用


這里需要注意,元組這個類型是比較特殊的,因為它是不可變的。
所以,當(dāng)我們指定Tuple[str, str]時,就只能傳入長度為2,并且元組中的所有元素都是str類型

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

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

from typing import NamedTuple


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


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

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

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中使用

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

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))

代碼中添加一個行新代碼,將一個字符串foo附加到整數(shù)列表中?,F(xià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的變量注釋語法,mypy仍將正確標(biāo)記該錯誤。你必須在#井號之后指定type:。如果你刪除它,那么它就不再是變量注釋了?;旧螾EP 526增加的所有內(nèi)容都為了使語言更加統(tǒng)一。

8、不足之處

雖然指定了 List[int] 即由 int 組成的列表,但是,實際中,只要這個列表中存在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 并沒有檢測出類型錯誤,沒有告警


annotations怎么在python3中使用mypy

工具 檢測到 類型異常,并進行了報錯


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)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

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

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

廣告

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

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