python 关键字参数为什么只能出现在最后_python – 请解释为什么这两个内置函数在关键字参数中传递时表现不同...

这是一个实现细节.

Python C API to retrieve arguments将位置和关键字参数分开.位置参数内部甚至没有名称.

用于检索operator.add函数(以及类似sub)的参数的代码是:

PyArg_UnpackTuple(a,#OP,2,2,&a1,&a2)

如您所见,它不包含任何参数名称.与operator.add相关的整个代码是:

#define spam2(OP,AOP) static PyObject *OP(PyObject *s, PyObject *a) { \

PyObject *a1, *a2; \

if(! PyArg_UnpackTuple(a,#OP,2,2,&a1,&a2)) return NULL; \

return AOP(a1,a2); }

spam2(op_add , PyNumber_Add)

#define spam2(OP,ALTOP,DOC) {#OP, op_##OP, METH_VARARGS, PyDoc_STR(DOC)}, \

{#ALTOP, op_##OP, METH_VARARGS, PyDoc_STR(DOC)},

spam2(add,__add__, "add(a, b) -- Same as a + b.")

如您所见,使用a和b的唯一位置是docstring.方法定义也不使用METH_KEYWORDS标志,该标志是接受关键字参数所必需的.

一般来说,你可以放心地假设一个基于python的函数,你知道一个参数名称将始终接受关键字参数(当然有人可以使用* args解包但创建一个函数doc,其中参数看起来正常),而C函数可能会也可能不会接受关键字参数.有多个参数或可选参数的函数接受后来/可选参数的关键字参数,这是很好的.但你几乎要测试它.

您可以在python-ideas mailinglist找到关于支持关键字参数的讨论.还有来自Guido van Rossum(Benevolent Dictator For Life又称Python的创建者)的声明:

Hm. I think for many (most?) 1-arg and selected 2-arg functions (and

rarely 3+-arg functions) this would reduce readability, as the example

of ord(char=x) showed.

I would actually like to see a syntactic feature to state that an

argument cannot be given as a keyword argument (just as we already

added syntax to state that it must be a keyword).

One area where I think adding keyword args is outright wrong: Methods of built-in types or ABCs and that are overridable. E.g. consider the pop() method on dict. Since the argument name is currently undocumented, if someone subclasses dict and overrides this method, or if they create another mutable mapping class that tries to emulate dict using duck typing, it doesn’t matter what the argument name is — all the callers (expecting a dict, a dict subclass, or a dict-like duck) will be using positional arguments in the call. But if we were to document the argument names for pop(), and users started to use these, then most dict sublcasses and ducks would suddenly be broken (except if by luck they happened to pick the same name).

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值