在浏览源代码时,我注意到 asyncio 库中使用了以下语法:
@coroutine
def sleep(delay, result=None, *, loop=None):
"""Coroutine that completes after a given time (in seconds)."""
if delay == 0:
yield
return result
if loop is None:
loop = events.get_event_loop()
future = loop.create_future()
h = future._loop.call_later(delay,
futures._set_result_unless_cancelled,
future, result)
try:
return (yield from future)
finally:
h.cancel()
Run Code Online (Sandbox Code Playgroud)
什么是*参数列表吗?
Chr*_*ris 10
这意味着后面*的参数是仅关键字参数。
考虑以下:
def test(delay, result=None, *, loop=None):
print(delay, result, loop)
Run Code Online (Sandbox Code Playgroud)
在这种情况下,test(1,2,2)会引发,TypeError因为它最多需要两个位置参数,即delay和result:
test(1,2,2)
Run Code Online (Sandbox Code Playgroud)
类型错误:test() 需要 1 到 2 个位置参数,但给出了 3 个
第三个参数或loop只能在用作关键字时分配:
test(1,2,loop=2)
# 1 2 2
# Works fine
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息,请参阅函数定义
| 归档时间: |
|
| 查看次数: |
822 次 |
| 最近记录: |