Python中函數參數類型和參數綁定

來源:互聯網
上載者:User

標籤:python   函數的參數   可變參   傳參   參數   模組   missing   參數綁定   item   

參數類型

Python函數的參數類型一共有五種,分別是:

  • POSITIONAL_OR_KEYWORD(位置參數或關鍵字參數)
  • VAR_POSITIONAL(可變參數)
  • KEYWORD_ONLY(關鍵字參數)
  • VAR_KEYWORD(可變關鍵字參數)
  • POSITIONAL_ONLY(位置參數)

 

下面用舉幾個例子解釋一下這5個參數類型的含義:

      

POSITIONAL_OR_KEYWORD如其名所見,既可以用位置傳參,也可以用關鍵字傳參,並且他沒有任何*的聲明

>>> def foo(name):...     print(name)...>>> foo("hello")hello>>> foo(name="hello")hello

  

VAR_POSITIONAL是可變參數,通過*來聲明,它會把接收到的值存入一個元組

>>> def foo(*args):...     print(args)...>>> foo(1, 2, 3, 4, 5)(1, 2, 3, 4, 5)

  

KEYWORD_ONLY只能通過關鍵字傳參,這種參數會在VAR_POSITIONAL參數類型的後面,而且不帶**首碼,如同語義,只能通過指定關鍵字來傳參,不可以用位置傳參

>>> def foo(n1, *, n2):...     print(n1, n2)...>>> foo("hello", n2="world")hello world

  

VAR_KEYWORD是可變關鍵字參數,通過首碼**來聲明,這種參數類型可以接收0個或多個參數,並存入一個字典

>>> def foo(**kwargs):...     for key, value in kwargs.items():...         print("%s=%s" % (key, value))...>>> foo(a=1, b=2, c=3)a=1b=2c=3

  

POSITIONAL_ONLY是第五個參數類型,但是它已經不重要了,因為高版本的Python無法建立一個POSITIONAL_ONLY類型的參數,但是有些使用C語言實現且不接收關鍵字參數的函數(如divmod)支援

 

從下面的例子,我們可以看到,新定義的foo函數,每個參數都對應到上面的一個類型

>>> def foo(name, *args, middle=None, **kwargs):...     print("name:", name)...     print("args:", args)...     print("middle:", middle)...     print("kwargs:", kwargs)...>>> foo("hello", 1, 2, 3, middle="world", a=1, b=2, c=3)name: helloargs: (1, 2, 3)middle: worldkwargs: {‘a‘: 1, ‘b‘: 2, ‘c‘: 3}>>> my_foo = {"name": "hello", "middle": "world", "a": "1", "b": "2", "c": "3"}>>> foo(**my_foo)name: helloargs: ()middle: worldkwargs: {‘a‘: ‘1‘, ‘b‘: ‘2‘, ‘c‘: ‘3‘}>>> from inspect import signature>>> sig = signature(foo)>>> for name, param in sig.parameters.items():...     print(param.kind, ":", name, ‘=‘, param.default)...POSITIONAL_OR_KEYWORD : name = <class ‘inspect._empty‘>VAR_POSITIONAL : args = <class ‘inspect._empty‘>KEYWORD_ONLY : middle = NoneVAR_KEYWORD : kwargs = <class ‘inspect._empty‘>

  

參數綁定

將函數的參數綁定到一個字典上

>>> def foo(name, *args, middle=None, **kwargs):...     print("name:", name)...     print("args:", args)...     print("middle:", middle)...     print("kwargs:", kwargs)...>>> my_foo = {"name": "hello", "middle": "world", "a": "1", "b": "2", "c": "3"}>>> from inspect import signature>>> sig = signature(foo)>>> bound_args = sig.bind(**my_foo)>>> for name, value in bound_args.arguments.items():...     print(name, ‘=‘, value)...name = hellomiddle = worldkwargs = {‘a‘: ‘1‘, ‘b‘: ‘2‘, ‘c‘: ‘3‘}>>> del my_foo["name"]>>> bound_args = sig.bind(**my_foo)Traceback (most recent call last):...TypeError: missing a required argument: ‘name‘

  

在inspect模組的協助下,展示了Python資料模型把實參綁定給函數調用的形參的機制,這與解譯器使用的機制相同,當我們刪除字典中的name,執行時會報錯缺少name參數

Python中函數參數類型和參數綁定

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.