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

标签 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)
    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/

相关文章:

ruby - 使用关键字参数确定方法的数量

python - 为什么不能在 f 字符串中使用 "await"?

python - Pandas DataFrame 表格垂直滚动条

python - 在 main 中链接函数调用。是 "Pythonic"吗?

python - 加速python的请求函数

python - 符合 PEP8 的长 f 字符串拆分

python - 特定 python 应用程序的安全串行端口

python - 在 MongoDB 投影函数中使用关键字参数

function - 使用相同变量定义函数的最优雅/有效的方法