Jef*_*off 12
函数可以使用位置参数和/或关键字参数。函数参数用于为函数提供在函数本身之外开发的值,即函数需要知道的值。对于给定的函数,分配给特定参数的实际值可能会从一次调用更改为下一次调用。
一个位置参数适用于通过在函数的参数列表中的序号位置指定值的地方。例如,x
和real
,imag
是这些函数定义中的位置参数:
sqrt(x) = x^0.5
complex(real, imag) = real + imag*im
一个关键字参数持有由其名称指定值的地方。最后一个(最右边的)位置参数出现在第一个关键字参数之前。分号 ( ;
) 标记关键字参数的开始,即使没有位置参数也是如此。当使用这两种参数时,分号将位置参数与关键字参数分开。例如,digitcount
和digits
是此函数定义中的关键字参数:
roundedstring(x; digitcount) = string(round(x, digits=digitcount))
这是一个仅使用关键字参数的示例:
function pathname(; dirpath, filename)
return joinpath(dirpath, filename)
end
dir_path = "/home/workfiles"
file_name = "current.txt"
path_name = pathname(dirpath=dir_path, filename=file_name)
# pathname == "/home/workfiles/current.txt"
Run Code Online (Sandbox Code Playgroud)
这是几乎相同的示例,使用两种参数:
function pathname(dirpath; filename)
return joinpath(dirpath, filename)
end
dir_path = "/home/workfiles"
file_name = "current.txt"
path_name = pathname(dir_path, filename=file_name)
# pathname == "/home/workfiles/current.txt"
Run Code Online (Sandbox Code Playgroud)
使用关键字参数的原因之一:
function copyfile(; source, dest)
# function body
end
src_pathname = "~/current.txt"
dst_pathname = "/home/workfiles/current.txt"
# now both of these work
copyfile(source = src_pathname, dest = dst_pathname)
copyfile(dest = dst_pathname, source = src_pathname)
Run Code Online (Sandbox Code Playgroud)
使用关键字参数来允许更改默认设置:
function translate(text; language="en")
# translation function body
end
Run Code Online (Sandbox Code Playgroud)
使用关键字参数来要求某些东西:
#=
If the keyword `language` is not specified
when calling this function, a error occurs.
=#
function translate(text; language)
# translation function body
end
Run Code Online (Sandbox Code Playgroud)
当在函数调用中省略参数时,这两种参数都可以使用默认值。所有未指定默认值的位置参数必须在所有指定默认值的位置参数之前。关键字参数具有相同的要求,任何具有默认值的都必须跟在所有未指定默认值的关键字参数之后。