【问题标题】:Python: Using defined arguments with *argsPython:使用带有 *args 的已定义参数
【发布时间】:2014-11-21 17:04:12
【问题描述】:

重写以更清楚用例并更好地回答 Anentropic 的问题。

def use_all (step_todo, wait_complete=True, *args):
    execute_step1 (step-todo)
    handle_args (*args)
    if not wait_complete: 
       do_somehing ()
       return
    execute_stepN ()

@decorate
def use_from (step_todo, *args):
    use_all (step_todo, args)

@decorate
def use_many ():
    use_all (step_todo1, wait_complete=False)
    use_all (step_todo2, args2)
    use_all (step_todo3)

use_all 是处理这些步骤的主要“执行者”(确切地说是pxssh 用于安装)。它不应装饰带有启动/停止 cmets,因为可能会从一个过程中多次调用(例如 step_many 这是重新启动 - 没有 wait_complete 的原因),但单步应该是。

由于用例是特定的,我可能会看到将*args 处理为包含元组的_single 命名变量的解决方案,例如

def use_all (step_todo, wait_complete=True, args_list=()):

这是正确的(和推荐的)解决方案吗?

这在某种程度上与问题 python function *args and **kwargs with other specified keyword argumentsUsing default arguments before positional arguments 相关联。是否可以解析kwargskeep Python R2.7?

谢谢 一月

【问题讨论】:

    标签: python python-2.7 args


    【解决方案1】:

    你需要这样做:

    def use_from(step_todo, *args):
        use_all(step_todo, *args)
    

    ...否则,您将使用包含值列表的单个 arg 调用 use_all,而不是使用多个 args 调用它

    另外,不要在你的函数和括号之间加空格,这是不好的风格:)

    要解决wait_complete 获取第一个参数的值的问题,您需要显式传递它,例如:

    def use_from(step_todo, *args):
        use_all(step_todo, True, *args)
    

    【讨论】:

    • 两者都好,但这仍然不能解决 wait_complete 取第一个 args 值的问题。
    • 是的,因此您将始终必须显式传递 wait_complete 的值
    • wait_complete 吃掉了第一个 arg,你可以这样称呼它use_all(step_todo, True, *args),但这实在是太难看了,我认为 use_all() 的参数列表需要重新设计。
    • 是的,所以基本上对 OP 的回答是“在 python 2.7 中不可能做到这一点”
    • 我没有看到 use_all 函数的意义,也许有一个更完整的例子我们可以提出一个有用的替代方案
    【解决方案2】:

    这在 Python 2.7 中是不可能的,但是在 python 3.x 中你可以:

    def use_all (step_todo, *args, wait_complete=True):
        print('W_C: {0}'.format(wait_complete))
        print('Args: {0}'.format(args))
    
    def use_from (step_todo, *args, **kwargs):
        use_all (step_todo, *args, **kwargs)
    
    use_from ('Step1')
    use_from ('Step3', 'aa:bb:cc')
    

    输出:

    >>> W_C: True
    >>> Args: ()
    >>> W_C: True
    >>> Args: ('aa:bb:cc',)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-09
      • 1970-01-01
      • 2021-10-15
      • 1970-01-01
      • 1970-01-01
      • 2021-01-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多