python限制引數型別

2021-10-01 08:45:05 字數 788 閱讀 1082

python3.5對型別進行標註了, 但是貌似不檢查具體型別是啥

下面的示例表示,name需要是str型別的, greeting()的返回值是str型別的, 但是傳入其他型別的變數也不會報錯, 只是起到了標註型別的作用

def

greeting

(name:

str)

->

str:

return

'hello '

+ name

進一步
# 限制了a的引數型別為list, 返回值型別為tuple

deftmp0

(a:list)-

>

tuple

:pass

# 複雜一點的寫法

from typing import list, tuple, dict

# 限制了返回值型別為列表, 並且列表的元素是int型別或者str型別

deftmp1

(a:float

, s:

str)

-> list[

intor

str]

:pass

# 限制了返回值為元組型別, 並且元組內的元素型別依次為元組,字典,字串,布林

deftmp2

(a:bool

, s:

str)

-> tuple[tuple, dict,

str,

bool]:

pass

python模組分析之typing

Python引數型別

位置引數 呼叫函式時根據函式定義的引數位置來傳遞引數 def print hello name,dict print hello s s,welcome to python world name,dict.get u 先生 兩個引數的順序必須一一對應,且少乙個引數都不可以 print hello t...

非型別模板引數的限制

c 非型別模板引數的限制在 c templates中有兩條 1.引數是常整數 包括列舉值 2.指向外部鏈結物件的指標 英文的原文 摘錄自c templates 4.3 如下 note that nontype template parameters carry some restrictions.i...

Python函式引數型別

函式的引數 定義函式 引數 普通引數,預設引數,可變引數 可變位置引數,可變關鍵字引數 keyword only 引數 呼叫函式 傳參 位置引數,關鍵字引數,引數結構 位置引數解構,關鍵字引數解構 普通引數 x,y def add x,y return x y 預設引數 x 1 def inc ba...