In Python, what does dict.pop(a,b) mean?

前端 未结 4 1084
既然无缘
既然无缘 2020-12-23 10:56
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.
         


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-23 11:43

    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).

提交回复
热议问题