gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 15:05:21 26 4
gpt4 key购买 nike

我正在尝试找出 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'))

在第一种情况下,一切正常:

My name is Mr. Baby, and my age is 0.8

在第二种情况下,person_name 参数作为字典出现,我不确定为什么:

My name is {'first_name': 'Chris'}, and my age is 42. My favorite movie is A new hope, and my favorite Jedi is Kit Fisto.

有没有一种方法可以在不显式覆盖每个“基本人类”参数的情况下完成这项工作?

def basic_human(first_name='Jeff', age=42, other_params=None):
if other_params:
if 'first_name' in other_params:
first_name = other_params['first_name']...
return f"My name is {first_name}, and my age is {age}"

最佳答案

为了通过 basic_human 函数传递 kwargs,您需要它也接受 **kwargs,以便调用它时接受任何额外参数。

其次,您必须以相同的方式传递 kwargs,即在将它们传递给 basic_human

时将它们解包为命名参数

像这样:

def basic_human(first_name='Jeff', age=42, **kwargs):
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'))

关于Python 在格式化字符串 : expect string, 中使用 kwargs get dict?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66251287/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com