hug2wisdom / learnpython

note the points of learn python
0 stars 0 forks source link

Function #7

Open hug2wisdom opened 4 years ago

hug2wisdom commented 4 years ago

In a function call, keyword arguments must follow positional arguments.

When a final formal parameter of the form **name is present, it receives a dictionary containing all keyword arguments except for those corresponding to a formal parameter. This may be combined with a formal parameter of the form*name which receives a tuple containing the positional arguments beyond the formal parameter list. (*name must occur before **name.)

eg:

def cheeseshop(kind, *arguments, **keywords):
    print("-- Do you have any", kind, "?")
    print("-- I'm sorry, we're all out of", kind)
    for arg in arguments:
        print(arg)
    print("-" * 40)
    for kw in keywords:
        print(kw, ":", keywords[kw])

cheeseshop("Limburger", "It's very runny, sir.",
           "It's really very, VERY runny, sir.",
           shopkeeper="Michael Palin",
           client="John Cleese",
           sketch="Cheese Shop Sketch") 

*agruments 在实际传实参的时候,不需要用 tuple 的形式,**keywords 在实际传参数的时候,也不需要用 dictionary 的形式,用关键字形式实参就行。

hug2wisdom commented 4 years ago

Unpacking Argument Lists

The reverse situation occurs when the arguments are already in a list or tuple but need to be unpacked for a function call requiring separate positional arguments. For instance, the built-in range() function expects separate start and stop arguments. If they are not available separately, write the function call with the* operator to unpack the arguments out of a list or tuple:

list(range(3, 6))            # normal call with separate arguments

args = [3, 6]
list(range(*args))            # call with arguments unpacked from a list

In the same fashion, dictionaries can deliver keyword arguments with the ** operator:

def parrot(voltage, state='a stiff', action='voom'):
    print("-- This parrot wouldn't", action, end=' ')
    print("if you put", voltage, "volts through it.", end=' ')
    print("E's", state, "!")

d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
parrot(**d)

有的时候需要将list,tuple,dictionary 格式的参数拆解开来作为实参,list 、tuple 使用 * 来操作,dictionary 使用 ** 来操作。

hug2wisdom commented 4 years ago

声明函数时,参数中星号*可以单独出现,例如:


def f(a,b,*,c):
    return a+b+c

如果单独出现星号 * 后的参数必须用关键字传入。

>>> def f(a,b,*,c):
...     return a+b+c
... 
>>> f(1,2,3)   # 报错
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: f() takes 2 positional arguments but 3 were given
>>> f(1,2,c=3) # 正常
6
hug2wisdom commented 4 years ago

lambda 函数拥有自己的命名空间,且不能访问自己参数列表之外或全局命名空间里的参数。