位置参数跟随关键字参数

46
我在Python中调用一个函数,像这样:
order_id = kite.order_place(
    self, exchange, tradingsymbol, transaction_type,
    quantity, price, product, order_type, validity,
    disclosed_quantity=None, trigger_price=None, squareoff_value, 
    stoploss_value, trailing_stoploss, variety, tag='')

这是函数文档中的代码示例:
def order_place(
    self, exchange, tradingsymbol, transaction_type,
    quantity, price=None, product=None, order_type=None, validity=None,
    disclosed_quantity=None, trigger_price=None, squareoff_value=None,
    stoploss_value=None, trailing_stoploss=None, variety='regular', tag='')

出现了这样的错误:
  File "csvr.py", line 7
    stoploss_value, trailing_stoploss, variety, tag='')
                                                      ^
SyntaxError: positional argument follows keyword argument

如何解决这个错误?
1个回答

59

语言的语法规定在调用中位置参数出现在关键字参数或星号参数之前:

argument_list        ::=  positional_arguments ["," starred_and_keywords]
                            ["," keywords_arguments]
                          | starred_and_keywords ["," keywords_arguments]
                          | keywords_arguments

具体来说,关键字参数看起来像这样:tag='内幕交易!'而位置参数看起来像这样:...,交易所,...
问题在于您似乎复制/粘贴了参数列表,并保留了一些默认值,这使它们成为了关键字参数。这没问题,但是您接下来又回到了使用位置参数,这是语法错误。
另外,当一个参数有一个默认值,比如disclosed_quantity=None,这意味着您不必提供它。如果您不提供它,它将使用默认值。
另外,self是特殊处理的,可以省略。
order_id = kite.order_place(
    exchange, tradingsymbol, transaction_type,
    quantity, price, product, order_type, validity,
    squareoff_value, 
    stoploss_value, trailing_stoploss, variety)

另一个选择是将您的后续位置参数转换为关键字参数:
order_id = kite.order_place(
    exchange, tradingsymbol, transaction_type,
    quantity, price, product, order_type, validity,
    disclosed_quantity=None,
    trigger_price=None,
    squareoff_value=squareoff_value,
    stoploss_value=stoploss_value,
    trailing_stoploss=trailing_stoploss,
    variety=variety,
    tag='')

或者你甚至可以为所有内容使用关键字参数:
order_id = kite.order_place(
    exchange=exchange,
    tradingsymbol=tradingsymbol,
    transaction_type=transaction_type,
    quantity=quantity,
    price=price,
    product=product,
    order_type=order_type,
    validity=validity,
    disclosed_quantity=None,
    ...

3
这是正确的,@Ardour Technologies请标记为正确。总结他的意思 - 你可以这样指定参数:function1("arg1", "arg2", "arg3") 或者你可以这样指定它们:function1(arg3="arg3", arg1="arg1", arg2="arg2"(假设每个参数都是可选的)。 - 255.tar.xz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接