Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用splat运算符传递可选参数无法按预期工作_Python - Fatal编程技术网

Python 使用splat运算符传递可选参数无法按预期工作

Python 使用splat运算符传递可选参数无法按预期工作,python,Python,我有一个通用函数,它接受2个参数(int)作为a和B作为必需参数,另外2个作为可选参数;这是函数signatute myfunct(a, b, c=False, d="joe") a和b是int型,c是bool型,d是str型 我正在使用splat操作符传递一个列表,因此根据从argparse获得的参数数量,我可以添加可选参数,也可以不添加。有时,我会得到对函数的调用 myfunct 21, 32 有时作为 myfunct 34, 44, c=True 以及介于两者之间的所有其他变体 尽管

我有一个通用函数,它接受2个参数(int)作为a和B作为必需参数,另外2个作为可选参数;这是函数signatute

myfunct(a, b, c=False, d="joe")
a和b是int型,c是bool型,d是str型

我正在使用
splat
操作符传递一个列表,因此根据从
argparse
获得的参数数量,我可以添加可选参数,也可以不添加。有时,我会得到对函数的调用

myfunct 21, 32
有时作为

myfunct 34, 44, c=True
以及介于两者之间的所有其他变体

尽管我注意到splat函数没有正确地传递可选参数。相反,它会按顺序传递参数,即使我指定使用哪个可选参数

thelist = [21, 32, "d="+"mike"]

myfunct(*thelist]
当我查看函数中每个变量中得到的内容时,我正确地得到了
a
b
,但不是在
d
可选参数中得到
mike
,而是在
c
中得到它,它分配整个字符串,而不仅仅是
=/code>符号后面的内容

这就是变量的内容:

a -> 21
b -> 32
c -> d=mike
在我期待的时候

a -> 21
b -> 32
d -> mike

如何使用splat运算符传递可选参数?或者这是一个坏主意吗?

通过dict给出关键字参数(kwargs),并用
**
展开:

args = [21, 32]
kwargs = {"d": "mike"}
myfunct(*args, **kwargs)

通过dict给出关键字参数(KWARG),扩展为
**

args = [21, 32]
kwargs = {"d": "mike"}
myfunct(*args, **kwargs)

虽然可以为位置参数解包一个列表(这一点您显然已经了解),但对于关键字参数,您需要一个字典

args = [21, 32]
kwargs = {"c": "mike"}

def test_function(a, b, c=None):
    print(a, b, c)

test_function(*args, **kwargs)
# (21, 32, 'mike')

这本身并不是一个坏主意,但是当你做类似的事情时,一定要记住它会对查看你的代码的人的可读性产生怎样的影响(包括你自己在几个月后,这已经不再是你脑海中的新鲜事)。

虽然可以为位置参数解压列表,很明显,对于关键字参数,你需要一本字典

args = [21, 32]
kwargs = {"c": "mike"}

def test_function(a, b, c=None):
    print(a, b, c)

test_function(*args, **kwargs)
# (21, 32, 'mike')

这本身并不是一个坏主意,但当你做这样的事情时,一定要记住它会如何影响别人看你的代码的可读性(包括你自己在几个月后,这已经不再是你脑海中的新鲜事)。

使用
**
和口述
**
和口述,我不知道有两颗星,这本字典在这种情况下会有用。谢谢太棒了,我不知道有两颗星,这本字典在这种情况下会有用。谢谢