簡體   English   中英

與形式(位置),* args和** kwargs一起使用時,顯式傳遞命名(關鍵字)參數

[英]Explicit passing named (keyword) arguments when used with formal (positional), *args and **kwargs

我有以下代碼:

#!/usr/bin/python

import sys
import os

from pprint import pprint as pp

def test_var_args(farg, default=1, *args, **kwargs):
    print "type of args is", type(args)
    print "type of args is", type(kwargs)

    print "formal arg:", farg
    print "default arg:", default

    for arg in args:
        print "another arg:", arg

    for key in kwargs:
        print "another keyword arg: %s: %s" % (key, kwargs[key])

    print "last argument from args:", args[-1]


test_var_args(1, "two", 3, 4, myarg2="two", myarg3=3)

上面的代碼輸出:

type of args is <type 'tuple'>
type of args is <type 'dict'>
formal arg: 1
default arg: two
another arg: 3
another arg: 4
another keyword arg: myarg2: two
another keyword arg: myarg3: 3
last argument from args: 4

如您所見,默認參數傳遞為“ two”。 但是,除非明確說明,否則我不希望為默認變量分配任何內容。 換句話說,我希望上述命令返回以下內容:

type of args is <type 'tuple'>
type of args is <type 'dict'>
formal arg: 1
default arg: 1
another arg: two
another arg: 3
another arg: 4
another keyword arg: myarg2: two
another keyword arg: myarg3: 3
last argument from args: 4

更改默認變量應該顯式完成,例如,使用類似這樣的命令(以下命令會導致編譯錯誤,這只是我的嘗試) test_var_args(1, default="two", 3, 4, myarg2="two", myarg3=3)

type of args is <type 'tuple'>
type of args is <type 'dict'>
formal arg: 1
default arg: two
another arg: 3
another arg: 4
another keyword arg: myarg2: two
another keyword arg: myarg3: 3
last argument from args: 4

我嘗試了以下操作,但它還會返回編譯錯誤: test_var_args(1,, 3, 4, myarg2="two", myarg3=3)

這可能嗎?

不幸的是,我認為這是不可能的。

正如Sam所指出的那樣,您可以通過消除浪費來實現相同的行為。 如果您的邏輯依賴包含“默認”參數的kwargs,則可以使用pop方法將其從kwargs字典中刪除(請參見此處 )。 以下代碼的行為如您所願:

import sys
import os

from pprint import pprint as pp

def test_var_args(farg, *args, **kwargs):
    print "type of args is", type(args)
    print "type of args is", type(kwargs)

    print "formal arg:", farg
    print 'default', kwargs.pop('default', 1)

    for arg in args:
        print "another arg:", arg

    for key in kwargs:
        print "another keyword arg: %s: %s" % (key, kwargs[key])

    print "last argument from args:", args[-1]

# Sample call
test_var_args(1, 3, 4, default="two", myarg2="two", myarg3=3)

運作方式與您在問題中的要求相似

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM