你希望函数的某些参数强制使用关键字参数传递:
将强制关键字参数放到某个*参数或者当个*后面就能达到这种效果:
def dog(name, host, *, age):
print(name, host, age)
参数中有一个 “*” 号,在该符号之后的所有参数(可一至多个)均被称为强制关键字参数,如果按照位置参数的方式对这些参数传值:
[root@node01 python]# cat s1.py
def dog(name, host, *, age):
print(name, host, age)
dog('a','b',23)
[root@node01 python]# python3.6 s1.py
Traceback (most recent call last):
File "s1.py", line 3, in <module>
dog('a','b',23)
TypeError: dog() takes 2 positional arguments but 3 were given
[root@node01 python]#
[root@node01 python]# cat s1.py
def dog(name, host, *, age):
print(name, host, age)
dog('dobi', 'xuzhoufeng', age = 2)
[root@node01 python]# python3.6 s1.py
dobi xuzhoufeng 2
[root@node01 python]# cat s2.py
def recv(maxsize, *, block):
print (maxsize,block)
recv(1,2)
[root@node01 python]#
[root@node01 python]# python3.6 s2.py
Traceback (most recent call last):
File "s2.py", line 3, in <module>
recv(1,2)
TypeError: recv() takes 1 positional argument but 2 were given
[root@node01 python]# cat s2.py
def recv(maxsize, *, block):
print (maxsize,block)
recv(1,block=2)
[root@node01 python]# python3.6 s2.py
1 2