为什么我们在Python中使用**来解包? [已关闭]

问题描述 投票:0回答:2

根据我的经验,拆包

**
是没有用的。

所以请阅读我的问题并告诉我为什么我们使用它们,或者给我一个例子,其中两个星号很有用。

为什么我们在 Python 函数中使用

**
进行解包,而无需它们也能得到相同的结果?

示例

dict1 = {"brand": "Ford", "model": "Mustang", "year": 1964}
def func(args):
    for i in args.items():
        print(i)

func(dict1)

上一个函数将得到与以下函数相同的结果:

dict1 = {"brand": "Ford", "model": "Mustang", "year": 1964}
def func(**args):
    for i in args.items():
        print(i)

func(**dict1)
python function unpack
2个回答
1
投票

这在您的函数中不是问题,因为您显式地迭代传递的字典,但对于一般情况,

*
用于解包
args
**
用于解包
kwargs
/关键字参数。


这可以从下面的结果看出 -

  1. 使用 ** 解压关键字参数会将每个键映射到相应的关键字参数。这将返回函数中定义的相应参数的值。
def func(brand, model, year):
    return brand, model, year
    
dict1 = {"brand": "Ford", "model": "Mustang", "year": 1964}
print(func(**dict1))

#OUTPUT: ('Ford', 'Mustang', 1964)
  1. 单个 * 仅将字典解压到其键。因此,当传递这些键时,函数会以字符串形式返回键。在这种情况下,用于传递参数的正确数据结构将是列表或元组。
dict1 = {"brand": "Ford", "model": "Mustang", "year": 1964}
print(func(*dict1))

#OUTPUT: ('brand', 'model', 'year')
  1. 如果不解压,这种情况会失败,因为模型需要 3 个参数,但只得到 1 个(字典)。
dict1 = {"brand": "Ford", "model": "Mustang", "year": 1964}
print(func(dict1))

#OUTPUT:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-731-f73ee817438f> in <module>
      1 dict1 = {"brand": "Ford", "model": "Mustang", "year": 1964}
----> 2 print(func(dict1))

TypeError: func() missing 2 required positional arguments: 'model' and 'year'

0
投票

您通常不会在不需要与其他任何东西集成的函数的 API 中包含

**args
。您通常会使用它以某种不关心确切参数行为的方式包装/与另一个函数交互。例如,考虑以下人为的示例:

@memoize
def f(a=0, b=0):
    if a==0: return b
    return a * f(a-1, b-a)

def memoize(f):
    cache = {}
    def _f(**kwargs):
        t = tuple(kwargs.items())
        if t not in cache:
            cache[t] = f(**kwargs)
        return cache[t]
    return _f

使用

**kwargs
而不是传入字典的主要优点是,记忆函数与其包装的函数具有完全相同的 API,因此调用者无法合理地区分它们。

正如您所指出的,从实现的角度来看,这两种约定没有太大的功能差异——区别在于您向外界公开的 API(性能也可能有所不同,但据我所知我认为与其他提高性能的方法相比,不值得关注如此小的收益)。在某些地方,这可能根本不重要,而在其他地方,您可能有充分的理由选择一种策略而不是另一种。

© www.soinside.com 2019 - 2024. All rights reserved.