python: 让函数必须只接受关键字参数传参

如何编写一个只接受关键字参数的函数

为什么有这个需求?

因为有时候写了一函数,当你调用它时候,如果不通过关键字参数去传参时,你根本不知道这个参数是什么意思,这样的话可读性太差了

解决办法

只需要将关键字参数放在以*打头的参数或一个单独的*之后,这样的话,调用这个函数时,就必须以关键字参数传参,可读性就会大大增强

def read(size, *, block):
   print(block)
   
read(10, True)
Traceback (most recent call last):
 File "<input>", line 1, in <module>
TypeError: read() takes 1 positional argument but 2 were given

read(10, block=True)
True

猜你喜欢

转载自blog.csdn.net/weixin_42237702/article/details/91355353
今日推荐