在Python中,dict.pop(a,b)是什么意思? [英] In Python, what does dict.pop(a,b) mean?
问题描述
data = {'a':'aaa','b':'bbb','c':'ccc'}
def pop(self,key,* args):
return self.data.pop(key,* args)#what这是什么意思。
b = a()
打印b.pop('a',{'b':'bbb'})
打印b.data
self.data.pop(key,* args)
← ----为什么还有第二个参数?
pop
方法(如 self.data
,即 {'a':'aaa','b':'bbb','c' :'ccc'}
,这里)有两个参数 - 见文档
第二个参数默认
是什么 pop
如果第一个参数 key
不存在,则返回。
(如果你调用 pop
只有一个参数 key
,它会引发异常,如果该键不存在)
在您的示例中, print b.pop('a',{'b':'bbb'})
,这是不相关的,因为'a'
b.data
。但是如果你重复这一行...:
b = a()
print b.pop ',{'b':'bbb'})
print b.pop('a',{'b':'bbb'})
print b.data
你会看到它有所作为:第一个 pop
code>'a'键,所以在第二个 pop
默认
参数实际上是返回的(因为'a'
现在不在 b.data
中)。
class a(object):
data={'a':'aaa','b':'bbb','c':'ccc'}
def pop(self, key, *args):
return self.data.pop(key, *args)#what is this mean.
b=a()
print b.pop('a',{'b':'bbb'})
print b.data
self.data.pop(key, *args)
←------ why is there a second argument?
The pop
method of dicts (like self.data
, i.e. {'a':'aaa','b':'bbb','c':'ccc'}
, here) takes two arguments -- see the docs
The second argument, default
, is what pop
returns if the first argument, key
, is absent.
(If you call pop
with just one argument, key
, it raises an exception if that key's absent).
In your example, print b.pop('a',{'b':'bbb'})
, this is irrelevant because 'a'
is a key in b.data
. But if you repeat that line...:
b=a()
print b.pop('a',{'b':'bbb'})
print b.pop('a',{'b':'bbb'})
print b.data
you'll see it makes a difference: the first pop
removes the 'a'
key, so in the second pop
the default
argument is actually returned (since 'a'
is now absent from b.data
).
这篇关于在Python中,dict.pop(a,b)是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!