python函数参数类型有哪些,Python函数参数类型解析

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值