开发者

dictionary input of function in python

i have see some code like bellow:

params = {
    'username': username,
    'password': password,
    'attended': attended,
    'openid_identifier': openid_identifier,
    'multistage': (stage and True) or None
}
ret = authmethod.login(request, userobj, **params)

login is implemented like this

  def login(self,request,user_obj,**kw):
    username = kw.get('username')
    password = kw.get('password')

so we know that kw is a dictionary , but i don't know the *开发者_JAVA百科* meaning , is it something like pointer in C language ? is it used to input the dictionary as a reference .

thank you if you could answer me .


Basically this is what it means:

Without using **kw, you would need to list all the input parameters for login in it's signature.

Now, you are calling login function and you know what variable names login's parameters are. So if you have a lot of parameters, it's difficult to always remember the order of the parameters.

Therefore, you call login on parameters by naming the parameters' variable names and setting them equal to the value that you want to pass it. Think of it like this:

Without using **kw, you'd do this:

def say(phrase):
    print phrase

say("Hello, World!")

But, by using **kw, you can do this:

def say(**kw):
    phrase = kw.get('say_what')
    print phrase

say(**{'say_what':"Hello, World!"})

Now what happens is that using ** "unpacks the dictionary in such a way that it tells say that what it expects as the input parameter named say_what will have the value "Hello, World!".

The above example is not the best place to use **kw because there is only one input parameter. But if you have a function with a long signature, then it would be unreasonable to expect any programmer to remember exactly what parameters must be passed in what order to this function.

If (you and) the programmer were to use **kw, then the programmer can specify a dictionary which maps input the parameters' variable names (as strings) to their values. The function takes care of the rest and the programmer doesn't have to concern himself with the order in which he passes the parameters to the function

Hope this helps


These are called keyword arguments and they're described in lots of places, like the Python manual and in blog posts.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜