python语法错误* args与可选arg [英] python syntax error *args with optional arg
本文介绍了python语法错误* args与可选arg的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么这是一个语法错误??做这件事的合适方法是什么?
<预><代码>>>>def f(*args, option=None):文件<stdin>",第 1 行def f(*args, option=None):^语法错误:无效语法 解决方案
Python 2 不支持仅关键字参数.如果你真的希望你的 Python 2 函数有只能通过关键字传递的参数,你需要使用 **kwargs
并自己验证关键字参数:
def my_max(*args, **kwargs):'''模拟内置的最大值,包括仅关键字的键参数.'''key = kwargs.pop('key', None)如果夸格:raise TypeError('my_max() 得到了一个意外的关键字参数 {!r}'.format(next(iter(kwargs))))如果键是无:# max 不支持 key=None返回最大值(*参数)别的:return max(*args, key=key)
Why is this a syntax error?? What is the appropriate way to do this thing?
>>> def f(*args, option=None):
File "<stdin>", line 1
def f(*args, option=None):
^
SyntaxError: invalid syntax
解决方案
Python 2 doesn't have keyword-only argument support. If you really want your Python 2 function to have arguments that can only be passed by keyword, you need to take **kwargs
and validate the keyword arguments yourself:
def my_max(*args, **kwargs):
'''Emulate the built-in max, including the keyword-only key argument.'''
key = kwargs.pop('key', None)
if kwargs:
raise TypeError('my_max() got an unexpected keyword argument {!r}'.format(next(iter(kwargs))))
if key is None:
# max doesn't support key=None
return max(*args)
else:
return max(*args, key=key)
这篇关于python语法错误* args与可选arg的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文