Python 最好的特性之一就是提供了极为灵活的参数处理机制,而且 Python3 中进一步提供了仅限关键字参数;
下面来通过代码展示这些特性:
"""
从定位参数到仅限关键字参数;
"""def tag(name, *content, cls=None, **attrs):print('name: ', name)print('content: ', content)print('cls: ', cls)print('attrs: ', attrs)print('----------------------')# 传入单个定位参数:-------------------------------------------------------------
tag('Python')
# name: Python
# content: ()
# cls: None
# attrs: {}# 第一个参数后的任意数量的位置参数都会被 *content 捕获,存入一个元组:------------------
tag('Python', 'Java', 'Go')
# name: Python
# content: ('Java', 'Go')
# cls: None
# attrs: {}# 函数中没有明确指定名称的关键字参数,都会被 **attrs 捕获,存入一个字典:----------------
# cls 只能通过关键字参数传入
# 第一个位置参数也能通过关键字参数传入
tag(name='Python', id=3, cls='Language', level='M')
# name: Python
# content: ()
# cls: Language
# attrs: {'id': 3, 'level': 'M'}# Python3 新特性:* 之后的形参都只能通过关键字参数传入:------------------------------
def f(a, *, b):return a + bf(1, b=2) # 3
f(1, 2) # TypeError: f() takes 1 positional argument but 2 were givendef k(*, a, b):return a + bk(a=1, b=2) # 3
k(1, 2) # TypeError: k() takes 0 positional arguments but 2 were given