您可以在Javascript或Python中使用必需的关键字参数吗? [英] Can you have required keyword arguments in Javascript or Python?

查看:90
本文介绍了您可以在Javascript或Python中使用必需的关键字参数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以在javascript或python中使用必需的关键字参数吗?这是编程语言的共同特征,还是新颖而罕见?它们类似于在Ruby 2.1+中Ruby中关键字参数的实现.

Can you have required keyword arguments in javascript or python? Is this a common feature of programming languages, or is it new and rare? They would be analogous to this implementation of keyword arguments in 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-关键字参数)

我想知道,因为我对上一页作者的观点非常感兴趣.他基本上建议,必需的关键字参数可以帮助编码人员稍后互相理解对方的代码,而只会牺牲简洁性.就个人而言,我认为这是一个不错的权衡,我想知道它是否经常被采用.

I'd like to know because I was really interested in the perspective of the author of the above page. He basically suggests that required keyword arguments would help coders understand each other's code later on down the line, while only sacrificing succintness. Personally, I think that that is a decent trade off, and I wonder if it is commonly practiced or not.

我认为,很常见的情况是找到文档记录不充分的代码,并想知道哪个参数可以执行什么操作.这就是为什么我总是尝试在我的方法中使用简洁明了的说明.我可能会发疯,这是一个完全不必要的功能,毕竟,我只是一个新手编码员,当他懒惰时会编写脚本.

It is quite a common occurrence, I think, to find poorly documented code, and to wonder which argument does what. That's why I always try to put good and succinct instructions at my methods. I could be crazy and this is a completely unnecessary feature, after all, I'm just a newbie coder who scripts stuff when he gets lazy.

推荐答案

PEP-3102 引入了仅关键字参数" ,因此在Python 3.x中,您可以执行以下操作:

PEP-3102 introduced "keyword-only arguments", so in Python 3.x you could do:

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之前的版本)中,根本无法使用关键字参数.约定是定义一个位置参数,用户在其中传递对象文字:


In JavaScript (pre-ES6) there is no way to have keyword arguments at all. The convention for this would be to define a single positional argument into which the user passes an object literal:

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

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

and then pass an object literal as input. In use:

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

ES6使您可以通过 destructuring 来简化此操作,但据我所知,仍然没有对所需关键字参数的本机支持.

ES6 lets you simplify this a bit with destructuring, but there is still (as far as I'm aware) no native support for required keyword arguments.

这篇关于您可以在Javascript或Python中使用必需的关键字参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆