python:是否可能要求函数的参数都是关键字? [英] python: is it possible to require that arguments to the functions are all keyword?
本文介绍了python:是否可能要求函数的参数都是关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为了避免明显的错误,我想防止对某些函数使用位置参数。有没有办法实现这一点?
To avoid the obvious bugs, I'd like to prevent the use of positional arguments with some functions. Is there any way to achieve that?
推荐答案
只有Python 3可以做到这一点罚款):
Only Python 3 can do it properly (and you used the python3 tag, so it's fine):
def function(*, x, y, z):
print(x,y,z)
使用 ** kwargs
用户输入任何参数,除非稍后检查。此外,它将隐藏真实的参数名称。
using **kwargs
will let the user input any argument unless you check later. Also, it will hide the real arguments names from introspection.
** kwargs
不是这个问题的答案。
**kwargs
is not the answer for this problem.
测试程序:
>>> function(1,2,3)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
function(1,2,3)
TypeError: function() takes exactly 0 positional arguments (3 given)
>>> function(x=1, y=2, z=3)
1 2 3
这篇关于python:是否可能要求函数的参数都是关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文