Вопрос

I'm new to programming, hoping someone can help clarify some concept to help me learn.

I think I understand ** , the ** convert kwarg into keyword and then pass to function.

I'm not really sure why I need to use ** twice though. Specifically, why do I need to explicitly pass in **param (vs just param) when it was already in the function definition that I will be passing in an kwarg

class Main(webapp2.RequestHandler):
    def render(self, template, **kwarg):
        blah

class Test(Main):
    params = dict(a=1, b=2)
    self.render(template, params) #this doesn't work

    self.render(template, **params) 
    #this work, but I don't understand why do I need the ** again
    #when its already in the original render function?
Это было полезно?

Решение

The trick is that though the symbol (**) is the same, the operator is different:

def print_kwargs(**all_args):
    # Here ** marks all_args as the name to assign any remaining keyword args to
    print all_args

an_argument = {"test": 1}

# Here ** tells Python to unpack the dictionary
print_kwargs(**an_argument)

If we don't explicitly unpack our arguments in the call to print_kwargs then Python will throw a TypeError, because we have provided a positional argument that print_kwargs doesn't accept.

Why doesn't Python automatically unpack a dictionary into kwargs? Mostly because "explicit is better than implicit" - while you could do automatic unpacking for a **kwarg-only function, if the function had any explicit arguments (or keyword arguments) Python would not be able to automatically unpack a dictionary.

Другие советы

Let's say you have a method like this...

>>> def fuct(a, b, c):
...   print a
...   print b
...   print c

and you have got dictionary with required params to sent to method

d = {'a': 1, 'b': 2, 'c': 3}

so by using ** (double asteric) you can unpack the dictionary and send to function

>>> fuct(**d)
1
2
3
>>>

For the *args is used by the non-keyword arguments. A single * unpacks a list or tuple to elements, two *s unpack a dict to the keywords.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top