python - Unnamed Arguments in Functions: Equivalent of R's Triple Dot
问题描述
Coming from R
, I was wondering if there is an equivalent in Python of R
's ...
?
In R
, the triple dot can be quite useful in functions as it allows to pass any kind of arguments (named, unnamed, any type, any class, etc.). For example
fun <- function (...) return(list(...))
fun(a=1, b=2, weather=c("sunny", "warm"))
# returns
# $a
# [1] 1
# $b
# [1] 2
# $weather
# [1] "sunny" "warm"
Is there an analogous in Python?
I would like to have a similar function
def fun(...): return (...)
# such that
fun(a=1, b=2)
# returns
# {'a':1, 'b':2}
# or something similar
解决方案
This is the way to receive any number of arguments:
def function(*arguments):
print("received {} arguments".format(len(arguments)))
Then you can call it e.g. this way:
>>> function(5,5,6)
received 3 arguments
The arguments
variable is a tuple containing all of the arguments.
On the other hand, if you want named arguments, you can do this:
def function(**keyword_arguments):
print("received {} arguments".format(len(keyword_arguments)))
Then you can call it e.g. this way:
>>> function(a=4, b=7)
received 2 arguments
The keyword_arguments
variable contains a dictionary of passed arguments.
See also the Python Documentation on Keyword Arguments.
推荐阅读
- python - Python if 分支“期望一个缩进块”
- html - 将编辑和删除图标放置在图像下方
- php - 使用 xdebug 调试 ionCube 编码的 php 文件时出现 ERR_EMPTY_RESPONSE
- git - 防止 Jenkins 在构建运行时轮询 SCM (Git)
- javascript - 使用 Firestore 无限滚动
- javascript - 滚动时的滚动持续时间
- angular - 点击mailto时IE正在注销/刷新:角度
- performance-testing - 当单个脚本中的并发请求组中有多个 URL 时,如何在脚本中设置 SSL 版本?
- python - 在完整对象上使用 json.dumps 时出现 UnicodeDecodeError,仅在打印特定属性时工作正常
- regex - 如何从下面描述的日志文件中获取具体内容?