def foo(name, *args, **kwargs):
Run Code Online (Sandbox Code Playgroud)
*args
如果它的长度 ( len(args)
) 大于 2,我需要删除 的前两个参数。可以这样做吗?
这就是我需要这样做的原因:我有以下功能:
def foo(name, xml='my.xml', xsd='my.xsd', *otherfiles):
print('name: ' + name)
print('xml: ' + xml)
print('xsd: ' + xsd)
print(otherfiles)
Run Code Online (Sandbox Code Playgroud)
我需要向该函数的参数添加一个可选的布尔参数,而不破坏向后兼容性。所以我将函数更改为:
def foo2(name, *otherfiles, **kwargs):
kwargs.setdefault('relativePath', True)
if len(otherfiles)>0:
xml = otherfiles[0]
else:
kwargs.setdefault('xml', 'my.xml')
xml = kwargs['xml']
if len(otherfiles)>1:
xsd = otherfiles[1]
else:
kwargs.setdefault('xsd', 'my.xsd')
xsd = kwargs['xsd']
print('name: ' + name)
print('xml: ' + xml)
print('xsd: ' + xsd)
print(otherfiles)
Run Code Online (Sandbox Code Playgroud)
foo
现在我通过检查和 的输出是否foo2
相同来测试向后兼容性:
foo('my_name', '../my.xml', '../my.xsd', 'file1', 'file2')
print('===============================================================')
foo2('my_name', '../my.xml', '../my.xsd', 'file1', 'file2')
Run Code Online (Sandbox Code Playgroud)
输出:
name: my_name
xml: ../my.xml
xsd: ../my.xsd
('file1', 'file2')
===============================================================
name: my_name
xml: ../my.xml
xsd: ../my.xsd
('../my.xml', '../my.xsd', 'file1', 'file2')
Run Code Online (Sandbox Code Playgroud)
如您所见,应删除前两项otherfiles
以保留旧功能。
我们无法从 中删除项目,args
因为它就是tuple
。 因为tuple
是不可变的
但我们可以根据我们的逻辑创建包含项目的新变量args
。我们可以将新变量用于下一个过程。
演示1:
def foo(name, *args, **kwargs):
print "args: ", args
print "Type of args: ", type(args)
if len(args)>2:
tmp_args = args[0], args[1]
else:
tmp_args = args
print "Temp args:", tmp_args
print "Debug 1:"
foo("ww", 12,3,4,4,5,6,7,7)
print "\nDebug 2:"
foo("ss", 1)
Debug 1:
args: (12, 3, 4, 4, 5, 6, 7, 7)
Type of args: <type 'tuple'>
Temp args: (12, 3)
Debug 2:
args: (1,)
Type of args: <type 'tuple'>
Temp args: (1,)
Run Code Online (Sandbox Code Playgroud)
如果我们在下一个过程中不需要变量的值,我们可以覆盖相同的变量名,
演示2
def foo(name, *args, **kwargs):
print "args: ", args
print "Type of args: ", type(args)
if len(args)>2:
args = args[0], args[1] #- Created Same name variable.
print "Temp args:", args
Run Code Online (Sandbox Code Playgroud)