【发布时间】:2010-09-28 03:31:52
【问题描述】:
Python、C++、Scheme 等都允许您定义在参数列表末尾采用可变数量参数的函数...
def function(a, b, *args):
#etc...
...可以这样调用:
function(1, 2)
function(1, 2, 5, 6, 7, 8)
等... 是否有任何语言允许您在其他地方使用参数列表执行可变参数函数?像这样的:
def function(int a, string... args, int theend) {...}
所有这些都有效:
function(1, 2)
function(1, "a", 3)
function(1, "b", "c", 4)
另外,参数列表中任意位置的可选参数呢?
def function(int a, int? b, int c, int... d) {}
function(1, 2) //a=1, c=2, b=undefined/null/something, d=[]
function(1,2,3) //a=1, b=2, c=3,d=[]
function(1,2,3,4,5) //a=1, b=2, c=3, d=[4,5]
【问题讨论】:
-
为什么不直接使用数组\集合?
-
你可以。那么为什么在 Python/C++ 中有 *args 呢?人们似乎喜欢他们。
-
语法糖恕我直言;但每个人都有自己的:)
标签: programming-languages function arguments variadic-functions