你能在Javascript或Python中拥有必需的关键字参数吗?

时间:2016-06-15 07:55:32

标签: javascript python ruby keyword-argument

你能在javascript或python中使用必需的关键字参数吗?这是编程语言的一个共同特征,还是新的和罕见的?它们类似于Ruby in Ruby 2.1 +

中关键字参数的这种实现
def obvious_total(subtotal:, tax:, discount:)
  subtotal + tax - discount
end

obvious_total(subtotal: 100, tax: 10, discount: 5) # => 105

(以上示例直接来自https://robots.thoughtbot.com/ruby-2-keyword-arguments

我想知道,因为我对上一页作者的观点非常感兴趣。他基本上建议所需的关键字参数可以帮助编码人员稍后在线上理解彼此的代码,同时只会牺牲succintness。就个人而言,我认为这是一个不错的权衡,我想知道它是否普遍实践。

我认为,发现记录不佳的代码并且想知道哪个参数做了什么,这是很常见的事情。这就是为什么我总是试图在我的方法上加上简明扼要的指示。我可能会疯了,这是一个完全不必要的功能,毕竟,我只是一个新手编码器,当他懒惰时编写脚本。

1 个答案:

答案 0 :(得分:10)

PEP-3102引入了"仅限关键字的参数" ,因此在Python 3.x中你可以这样做:

def obvious_total(*, subtotal, tax, discount):
    """Calculate the total and force keyword arguments."""
    return subtotal + tax - discount

使用中:

>>> obvious_total(1, 2, 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: obvious_total() takes 0 positional arguments but 3 were given
>>> obvious_total(subtotal=1, tax=2, discount=3)
0

在JavaScript(ES6之前版本)中,根本无法获得关键字参数。对此的约定是定义用户传递对象文字的单个位置参数:

obviousTotal = function (input) {
    return input.subtotal + input.tax - input.discount
}

然后将对象文字传递为input。使用中:

> obviousTotal(1, 2, 3)
NaN  // because (1).subtotal etc. are undefined 
> obviousTotal({ subtotal: 1, tax: 2, discount: 3 })
0

ES6允许您通过解构进行一些简化,但仍然(据我所知)没有对所需关键字参数的原生支持。