Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.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在格式化字符串中使用kwargs:expect string,get dict?_Python_Keyword Argument_F String - Fatal编程技术网

Python在格式化字符串中使用kwargs:expect string,get dict?

Python在格式化字符串中使用kwargs:expect string,get dict?,python,keyword-argument,f-string,Python,Keyword Argument,F String,我试图找出kwargs,并做一些简单的字符串格式化 def basic_human(first_name='Jeff', age=42): return f"My name is {first_name}, and my age is {age}" def starwars_fan(movie='A new hope', jedi='Young Obi Wan', **kwargs): human_string = basic_human(kwargs)

我试图找出kwargs,并做一些简单的字符串格式化

def basic_human(first_name='Jeff', age=42):
    return f"My name is {first_name}, and my age is {age}"


def starwars_fan(movie='A new hope', jedi='Young Obi Wan', **kwargs):
    human_string = basic_human(kwargs)
    return f"{human_string}. My favorite movie is {movie}, and my favorite Jedi is {jedi}."

print(basic_human(first_name='Mr. Baby', age=0.8))
print(starwars_fan(person_name='Chris', jedi='Kit Fisto'))
在第一种情况下,一切正常:

我的名字是Baby先生,我的年龄是0.8岁

在第二种情况下,person_name参数作为dict输入,我不确定原因:

我的名字是{'first_name':'Chris'},我的年龄是42岁。我最喜欢的电影是《新希望》,我最喜欢的绝地武士是基特·菲斯托

有没有一种方法可以在不显式覆盖每个“基本人类”参数的情况下实现这一点

将其更改为:

human_string = basic_human(**kwargs)
kwargs
是一个包含所有剩余参数的
dict

print(kwargs)
# {'first_name': 'Chris'}
按照您编写的方式,
basic\u human
的第一个参数(
first\u name
)是这个dict,第二个(
age
)是42,而
其他参数仍然是
None

换句话说,您的版本相当于:

# What you got, not what you want.
basic_human(first_name={'first_name': 'Chris'}, age=42, other_params=None)

我的版本中的
**
的变化是它将dict扩展为参数。
kwargs
中的每个键都成为
basic_human
的命名参数,并具有相应的值。(有关详细信息,请参阅。)

为了通过
基本的_human
函数传递kwargs,您需要它也接受**kwargs,以便对它的调用可以接受任何额外的参数

其次,必须以相同的方式传递Kwarg,即在传递给
basic\u human

像这样:

def basic_human(名字叫杰夫,年龄42,**kwargs):
返回f“我的名字是{first_name},我的年龄是{age}”
def starwars_fan(电影《新希望》,《绝地武士》,《年轻的欧比万》,**kwargs):
人类字符串=基本人类(**kwargs)
return f“{human_string}。我最喜欢的电影是{movie},我最喜欢的绝地是{Jedi}。”
印刷品(基本的人类(名字是婴儿先生,年龄=0.8))
打印(星战迷(人名为克里斯,绝地为基特·菲斯托)

您必须打开
kwargs
的包装。您必须将其更改为
human\u string=basic\u human(**kwargs)
**
解压dict。您还可以使用带有
名字
绝地
键的dict,并使用
**
解压


此外,您还传递了不存在的
person\u name='Chris'
。你是说
first\u name='Chris'

你必须打开
kwargs
的包装。它将其更改为
human\u string=basic\u human(**kwargs)
。此外,您还传递了不存在的
person\u name='Chris'
。你是说
first\u name='Chris'
?嗨,你的问题回答了吗?如果是的话,请你接受并投票选出正确答案?如果没有,可以澄清什么?谢谢!我还没有意识到我需要打开它们,现在这个很好用。:)很高兴听到这个消息@如果其中一个回答了你的问题,请你用左边的复选标记“接受”它好吗?
# What you got, not what you want.
basic_human(first_name={'first_name': 'Chris'}, age=42, other_params=None)