python中start()方法_如何使用签名(例如[[start,] stop [,step])实现python方法,即左侧的默认关键字参数...

Since in python 3.X the build-id range() function returns no longer a list but an iterable, some old code fails as I use range()to conveniently generate lists I need.

So I try to implement my own lrange function like this:

def lrange(start = 0, stop, step = 1):

ret = []

while start < stop:

ret.append(start)

start += step

return ret

giving me a "non-default argument follows default argument" interpreter error.

If I look at Python's range() it seems to be possible.

I posted this question mainly because I was wondering if/how one can implement a function with such a signature on his own

解决方案

Quick Answer

This question popped up when I first started learning Python, and I think it worthwhile to document the method here. Only one check is used to simulate original behavior.

def list_range(start, stop=None, step=1):

if stop is None:

start, stop = 0, start

return list(range(start, stop, step))

I think this solution is a bit more elegant than using all keyword arguments or *args.

Explanation

Use a Sentinel

The key to getting this right is to use a sentinel object to determine if you get a second argument, and if not, to provide the default to the first argument while moving the first argument to the second.

None, being Python's null value, is a good best-practice sentinel, and the idiomatic way to check for it is with the keyword is, since it is a singleton.

Example with a proper docstring, declaring the signature/API

def list_range(start, stop=None, step=1):

'''

list_range(stop)

list_range(start, stop, step)

return list of integers from start (default 0) to stop,

incrementing by step (default 1).

'''

if stop is None:

start, stop = 0, start

return list(range(start, stop, step))

Demonstration

>>> list_range(10)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> list_range(5, 10)

[5, 6, 7, 8, 9]

>>> list_range(2, 10, 2)

[2, 4, 6, 8]

And it raises an error if no arguments are given, unlike the all-keyword solution here.

Caveat

By the way, I hope this is only considered from a theoretical perspective by the reader, I don't believe this function is worth the maintenance, unless used in a central canonical location to make code cross-compatible between Python 2 and 3. In Python, it's quite simple to materialize a range into a list with the built-in functions:

Python 3.3.1 (default, Sep 25 2013, 19:29:01)

[GCC 4.7.3] on linux

Type "help", "copyright", "credits" or "license" for more information.

>>> list(range(10))

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值