范围的奇怪参数 [英] the strange arguments of range
问题描述
python3 中的 range 函数接受三个参数.其中两个是可选的.所以参数列表看起来像:
[开始]、停止、[步骤]
这意味着(如果我错了,请纠正我)在非可选参数之前有一个可选参数.但是,如果我尝试定义这样的函数,我会得到:
<预><代码>>>>def foo(a = 1, b, c = 2):打印(a,b,c)语法错误:非默认参数遵循默认参数这是我作为普通"python 用户不能做的事情,还是我可以以某种方式定义这样的函数?我当然可以做类似的事情
def foo(a, b = None, c = 2):如果不是 b:乙 = 一一 = 1
但是例如帮助功能会显示奇怪的信息.所以我真的很想知道是否有可能定义一个像内置 range
这样的函数.
range()
接受 1 个位置参数和两个可选参数,并且解释这些参数取决于你传入了多少个参数.
如果只传入一个参数,则假定为stop
参数,否则第一个参数被解释为开始.
实际上,range()
, 用 C 编码,采用可变数量的参数.你可以像这样模拟:
def foo(*params):如果 3 2 其他 1
但你也可以交换参数:
def range(start, stop=None, step=1):如果停止是无:开始,停止 = 0,开始
The range function in python3 takes three arguments. Two of them are optional. So the argument list looks like:
[start], stop, [step]
This means (correct me if i'm wrong) there is an optional argument before a non-optional argument. But if i try to define a function like this i get this:
>>> def foo(a = 1, b, c = 2):
print(a, b, c)
SyntaxError: non-default argument follows default argument
Is this something I can't do as a 'normal' python user or can i somehow define such a function? Of course i could do something like
def foo(a, b = None, c = 2):
if not b:
b = a
a = 1
but for example the help function would then show strange informations. So i really want to know if it's possible do define a function like the built-in range
.
range()
takes 1 positional argument and two optional arguments, and interprets these arguments differently depending on how many arguments you passed in.
If only one argument was passed in, it is assumed to be the stop
argument, otherwise that first argument is interpreted as the start instead.
In reality, range()
, coded in C, takes a variable number of arguments. You could emulate that like this:
def foo(*params):
if 3 < len(params) < 1:
raise ValueError('foo takes 1 - 3 arguments')
elif len(params) == 1
b = params[0]
elif:
a, b = params[:2]
c = params[2] if len(params) > 2 else 1
but you could also just swap arguments:
def range(start, stop=None, step=1):
if stop is None:
start, stop = 0, start
这篇关于范围的奇怪参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!