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