【发布时间】:2015-09-20 23:19:46
【问题描述】:
我有以下代码:
#!/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
如您所见,默认参数是“两个”。但是我不想给默认变量分配任何东西,除非我明确地说出来。换句话说,我希望上述命令返回:
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)
这可能吗?
【问题讨论】:
-
将
default视为可选kwarg并在您的方法中包含default = kwargs.get('default', 1)行有什么问题? -
可能没什么,请您在回答中发布工作代码 sn-p。我尝试根据您的建议修改我的代码,并将此
default = kwargs.get('default', 1)添加为我在子例程中的第一行,但它返回我编译错误和/或在以下方式调用时将 3 作为默认值test_var_args(1, 3, 4, myarg2="two", myarg3=3, default="default") -
@WakanTanka 看看我的答案,它包含一个示例:D
-
谢谢你们,这有帮助