Python函数参数类型解析
python参数类型一共有五种:
POSITIONAL_OR_KEYWORD
VAR_POSITIONAL
VAR_KEYWORD
KEYWORD_ONLY
POSITIONAL_ONLY
(1)POSITIONAL_OR_KEYWORD:可以通过定位(位置)参数和关键字参数传入的形参,这是最常见的一种参数。
def power(x, n=2):
"""return x^n"""
sum = 1
for i in range(n):
sum *= x
return sum
#x与n都是Positional_or_keyword参数,可通过定位或关键字传参
power(5,2)#定位参数传参
power(x=2,n=10)#关键字传参
(2)VAR_POSITIONAL:定位参数元组,只能通过位置传参;参数格式如 *args;
VAR_KEYWORD:关键字参数字典,只能通过关键字参数传入;参数格式如 **kwargs;
KEYWORD_ONLY:仅限关键字参数,此参数前面存在VAR_POSITIONAL类型的参数;只能通过关键字传参。
def tag(name, *content, cls=None, **attrs):
"""html标签
name: or
content: content
cls:
attrs: such as "id=xxx"
"""
if cls is not None:
attrs['class'] = cls
if attrs:
attr_str = ''.join(' %s="%s"'%(attr,value)
for attr,value in sorted(attrs.items()))
else:
attr_str = ''
if content:
return '\n'.join('%s%s>'%(name,attr_str,c,name) for c in content)
else:
return ''%(name,attr_str)
在tag函数中:
name参数类型为VAR_POSITIONAL_OR_KEYWORD;
content参数类型为VAR_POSITIONAL;
cls参数类型为KEYWORD_ONLY;
attrs参数类型为VAR_KEYWORD;
tag函数调用方式
>>> tag('br')
'
'
>>> tag('h1','hello world')
'
hello world
'>>> print(tag('p','hello','world',cls='top'))
hello
world
>>> print(tag('p','hello','world',cls='top',id='keyword'))
hello
world
>>>
提取函数签名
>>> from inspect import signature
>>> sig = signature(tag)
>>> sig
>>> for name, param in sig.parameters.items():
... print("%s:%s=%s"%(param.kind,name,param.default))
...
POSITIONAL_OR_KEYWORD:name=
VAR_POSITIONAL:content=
KEYWORD_ONLY:cls=None
VAR_KEYWORD:attrs=
(3)VAR_POSITIONAL_ONLY:仅限定位参数,只能通过位置传参。
目前Python声明函数的句法不支持定义VAR_POSITIONAL_ONLY类型参数,但是有些使用C语言实现且不接受关键字参数的函数(divmod)支持。
>>> help(divmod)
Help on built-in function divmod in module builtins:
divmod(x, y, /)
Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
>>> divmod(x=20,y=8)
Traceback (most recent call last):
File "", line 1, in
TypeError: divmod() takes no keyword arguments
>>> divmod(20,8)
(2, 4)
>>>
标签:name,KEYWORD,Python,POSITIONAL,函数参数,参数,VAR,解析,cls
来源: https://blog.csdn.net/L_zzwwen/article/details/100068434