Python+Selenium学习笔记11 - python官网的tutorial - 定义函数
阅读原文时间:2023年07月10日阅读:2

1 def f(a, L=[]):
2 L.append(a)
3 return L
4
5 print f(5)
6 print f(2)

输出

1 def f(a, L=None):
2 if L is None:
3 L = []
4 L.append(a)
5 return L
6
7 print f1(5)
8 print f1(2)

输出

上面两个函数的区别,f()输出的结果是累加的,f1()输出的结果是独立的

If you don’t want the default to be shared between subsequent calls -> 用f1()

4.7.2. Keyword Arguments

def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
print("-- This parrot wouldn't", action, end=' ')
print("if you put", voltage, "volts through it.")
print("-- Lovely plumage, the", type)
print("-- It's", state, "!")

parrot(1000) # 1 positional argument
parrot(voltage=1000) # 1 keyword argument
parrot(voltage=1000000, action='VOOOOOM') # 2 keyword arguments
parrot(action='VOOOOOM', voltage=1000000) # 2 keyword arguments
parrot('a million', 'bereft of life', 'jump') # 3 positional arguments
parrot('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword

# 异常情况,下面几种情况运行都不成功

parrot() # required argument missing ,必须有个必填参数
parrot(voltage=5.0, 'dead') # non-keyword argument after a keyword argument ,这个当我把第二个参数换成status='dead'时运行成功。我的理解是前面参数用了参数名,后面就必须得跟,要是前面没跟,那后面跟不跟都可以
parrot(110, voltage=220) # duplicate value for the same argument,重复传参
parrot(actor='John Cleese') # unknown keyword argument #参数typo

输出

解析

传值时,带变量voltage=1000,运行时会自动匹配到对应的位置

不带变量parrot('a million', 'bereft of life', 'jump') ,则按顺序传参

定义函数有 *name和 **name时, *name 必须在 **name之前。

1 def cheeseshop(kind, *arguments, **keywords):
2 print("-- Do you have any", kind, "?")
3 print("-- I'm sorry, we're all out of", kind)
4 for arg in arguments:
5 print(arg)
6 print("-" * 40)
7 for kw in keywords:
8 print(kw, ":", keywords[kw])
9
10 cheeseshop("Limburger", "It's very runny, sir.",
11 "It's really very, VERY runny, sir.",
12 shopkeeper="Michael Palin",
13 client="John Cleese",
14 sketch="Cheese Shop Sketch")
15
16 # 输出结果
17 -- Do you have any Limburger ?
18 -- I'm sorry, we're all out of Limburger
19 It's very runny, sir.
20 It's really very, VERY runny, sir.
21 ----------------------------------------
22 shopkeeper : Michael Palin
23 client : John Cleese
24 sketch : Cheese Shop Sketch

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器