Python:kwargs.pop() 和 kwargs.get() 之间的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49218302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: Difference between kwargs.pop() and kwargs.get()
提问by Aliquis
I have seen both ways but I do not understand what the difference is and what I should use as "best practice":
我已经看到了两种方式,但我不明白有什么区别以及我应该将什么用作“最佳实践”:
def custom_function(**kwargs):
foo = kwargs.pop('foo')
bar = kwargs.pop('bar')
...
def custom_function2(**kwargs):
foo = kwargs.get('foo')
bar = kwargs.get('bar')
...
回答by DhiaTN
get(key[, default]): return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a
KeyError
.
get(key[, default]):如果键在字典中,则返回键的值,否则返回默认值。如果未给出默认值,则默认为 None,因此此方法永远不会引发
KeyError
.
d = {'a' :1, 'c' :2}
print(d.get('b', 0)) # return 0
print(d.get('c', 0)) # return 2
pop(key[, default])if key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a
KeyError
is raised.
pop(key[, default])如果键在字典中,删除它并返回它的值,否则返回默认值。如果未给出默认值并且键不在字典中,
KeyError
则引发 a。
d = {'a' :1, 'c' :2}
print(d.pop('c', 0)) # return 2
print(d) # returns {'a': 1}
print(d.get('c', 0)) # return 0
NB:Regarding best practice question, I would say it depends on your use case but I would go by default for .get
unless I have a real need to .pop
注意:关于最佳实践问题,我会说这取决于您的用例,但我会默认为.get
除非我真的需要.pop
回答by shx2
The difference is pop
also removes the item from the dict.
不同之处pop
还在于从字典中删除了该项目。
There is no best practice. Use the one which is more convenient for your particular use case.
没有最佳实践。使用对您的特定用例更方便的一种。
Most times, all you need is get
ting the value.
大多数时候,您所需要的只是get
调整价值。
Other times, you want to make sure no extra/unexpected kwargs are provided. In this case, it is convenient to use pop
. E.g.:
其他时候,你想确保没有提供额外/意外的 kwargs。在这种情况下,使用pop
. 例如:
a = kw.pop('a')
b = kw.pop('b')
if kw:
raise TypeError('Unepxected kwargs provided: %s' % list(kw.keys()))
回答by ssoler
Consider the next example, where the use of get
or pop
makes a difference:
考虑下一个示例,其中使用get
orpop
有所不同:
Let's begin with get
:
让我们开始get
:
class Foo(object):
def __init__(self, foo_param=None):
print("In Foo: {}".format(foo_param))
class Bar(Foo):
def __init__(self, **kwargs):
bar_param = kwargs.get('bar_param')
print("In Bar: {}".format(bar_param))
super(Bar, self).__init__(**kwargs)
bar = Bar(foo_param='F', bar_param='B')
This code snippet raises TypeError
exception:
此代码片段引发TypeError
异常:
TypeError: __init__() got an unexpected keyword argument 'bar_param'
When Bar executes super(Bar, self).__init__(**kwargs)
it is forwarding to Foo the same dict he has recived: {foo_param='F', bar_param='B'}
. Then Foo raises TypeError
because input paramteres doesn't respect its interface.
当 Bar 执行时,super(Bar, self).__init__(**kwargs)
它会向 Foo 转发他收到的同一个 dict: {foo_param='F', bar_param='B'}
。然后 Foo 引发,TypeError
因为输入参数不尊重其接口。
If you pop
bar_param
before executing the call to super
, Foo only recives its required input parameter foo_param
, and all goes fine.
如果您pop
bar_param
在执行对 的调用之前super
, Foo 只接收其所需的输入参数foo_param
,并且一切正常。
class Foo(object):
def __init__(self, foo_param=None):
print("In Foo: {}".format(foo_param))
class Bar(Foo):
def __init__(self, **kwargs):
bar_param = kwargs.pop('bar_param')
print("In Bar: {}".format(bar_param))
super(Bar, self).__init__(**kwargs)
bar = Bar(foo_param='F', bar_param='B')
Output is:
输出是:
In Bar: B
In Foo: F
回答by hwhite4
So the get and pop functions do very different things
所以 get 和 pop 函数做了非常不同的事情
get is used to return a value for a given key in the dictionary
get 用于返回字典中给定键的值
pop removes the value from the dictionary and returns the removed value
pop 从字典中移除值并返回移除的值
All of the dictionary functions are documented here (for python3): https://docs.python.org/3/library/stdtypes.html#mapping-types-dict
此处记录了所有字典函数(对于 python3):https: //docs.python.org/3/library/stdtypes.html#mapping-types-dict