天天看點

在python中pop是什麼意思_在Python中,dict.pop(a,b)是什麼意思?

So many questions here. I see at least two, maybe three:

What does pop(a,b) do?/Why are there a second argument?

What is *args being used for?

The first question is trivially answered in the Python Standard Library reference:

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.

The second question is covered in the Python Language Reference:

If the form “*identifier” is present,

it is initialized to a tuple receiving

any excess positional parameters,

defaulting to the empty tuple. If the

form “**identifier” is present, it is

initialized to a new dictionary

receiving any excess keyword

arguments, defaulting to a new empty

dictionary.

In other words, the pop function takes at least two arguments. The first two get assigned the names self and key; and the rest are stuffed into a tuple called args.

What's happening on the next line when *args is passed along in the call to self.data.pop is the inverse of this - the tuple *args is expanded to of positional parameters which get passed along. This is explained in the Python Language Reference:

If the syntax *expression appears in

the function call, expression must

evaluate to a sequence. Elements from

this sequence are treated as if they

were additional positional arguments

In short, a.pop() wants to be flexible and accept any number of positional parameters, so that it can pass this unknown number of positional parameters on to self.data.pop().

This gives you flexibility; data happens to be a dict right now, and so self.data.pop() takes either one or two parameters; but if you changed data to be a type which took 19 parameters for a call to self.data.pop() you wouldn't have to change class a at all. You'd still have to change any code that called a.pop() to pass the required 19 parameters though.