在Python中同时使用显式参数和**kwargs

3

我有这段代码:

kwargs_input = {"name": "lala", "age": 25, "postcode": 17867}

def print_kwargs(**kwargs):
    for k,v in kwargs.items():
        print(k,v)

def func_print(name="lolo", age=56, **kwargs):
    print_kwargs(**kwargs)

print(func_print(**kwargs_input))

打印输出:

postcode 17867
None

我有两个问题:

  1. 为什么 nameage 没有被打印出来?我期望通过传递给 **kwargs_input 的参数覆盖 name (lolo) 和 age (56) 的默认值。这是可能的吗?
  2. None 是从哪里来的?
3个回答

9
  1. 在函数调用过程中,nameage已从kwargs中移除,因此它们都未被打印。在函数调用内部,您可以通过这些变量访问nameage。而kwargs将包含其余的“变量”。
  2. func_print()默认返回None,而您的print(func_print())会将其打印出来。

我该怎么做才能让 kwargs 有默认值?例如,如果我在 kwargs_input 中没有设置 name,我希望 kwargs 取默认值,即 lolo - eng2019
你可以在函数内部添加:kwargs['name'] = name(对于每个带有默认值的参数都是如此),以便使用所有参数更新kwargs - quamrana

2

nameage没有被打包到第一个kwargs中,因此不会传递给其他函数。换句话说,它没有收集所有参数,而只收集未指定的参数,即“悬挂”参数,以避免出现错误。类似于C语言中的Varargs

None来自于func_print()的返回值,因为它是任何函数的默认值。

例如:

def func():
    ...  # check help(...) and type(...)
    # implicit "return None"

def func():
    pass
    # implicit "return None"

def func():
    return
    # implicit "return None"

def func():
    # explicit return None
    return None

您可以采用JavaScript中常用的方式,将一个对象作为参数传递。幸运的是,您不需要创建或传递自定义对象实例之类的内容,因为**kwargs本身就是一种语法,它会创建一个字典(或者*args会创建一个元组),从而保留了对象实例中的参数信息。(同样,您可以使用*args来传递位置参数,关于这方面的更多信息可以在这里找到。)
根据此方法,您可以进行如下操作:
def other(**kwargs):
    print(kwargs)

def func(**kwargs):
    print(kwargs.get("name", "lolo"))
    other(**kwargs)

print(func(name=123, hello="world"))
# 123
# {'name': 123, 'hello': 'world'}
# None
print(func(hello="world"))
# lolo
# {'hello': 'world'}
# None

0
重点在于Python中的**dict将字典展开为函数调用中的键值对。
kwargs_input = {"name": "lala", "age": 25, "postcode": 17867}

def print_kwargs(**kwargs):
    for k,v in kwargs.items():
        print(k,v)

def func_print(name="lolo", age=56, **kwargs):
    print_kwargs(**kwargs)

# Equivalent to passing **kwargs_input
print(func_print(name='lala', age=25, postcode=17867))

**kwargs 然后捕获所有在函数定义中未指定的“额外”关键字参数。

正如您所看到的 nameage


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接