官网摘录
1. 参数默认值
name = 'default'
def ask_ok(prompt, retries=4, reminder='Please try again!'):
while True:
ok = input(prompt)
if ok in ('y', 'ye', 'yes'):
return True
if ok in ('n', 'no', 'nop', 'nope'):
return False
retries = retries - 1
if retries < 0:
raise ValueError('invalid user response')
print(reminder)
2. 关键字参数
*arguments: 接收一个元组
**keywords: 接收一个字典
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")
-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
shopkeeper : Michael Palin
client : John Cleese
sketch : Cheese Shop Sketch
3. 特殊参数 - 官方文档
/ 和 *
仅限位置形参的名称可以在 **kwds
中使用而不产生歧义
/** 最常见的形式 **/
def standard_arg(arg):
print(arg)
standard_arg(3) // 可以运行
standard_arg(arg=3) // 可以运行
/** 带有'/', 仅使用位置形参 **/
def pos_only_arg(arg, /):
print(arg)
pos_only_arg(1) // 可以运行
pos_only_arg(arg=1) // 不能运行
/** 带有'*', 仅使用关键字限定 **/
def kwd_only_arg(*, arg):
print(arg)
kwd_only_arg(2) // 不能运行
kwd_only_arg(arg=2) // 可以运行
/** 既有'*'又有'/' **/
def combined_example(pos_only, /, standard, *, kwd_only):
print(pos_only, standard, kwd_only)
combined_example(1,2,3) // 不能运行
combined_example(1, 2, kwd_only=3) // 可以运行
combined_example(1, standard=2, kwd_only=3) // 可以运行
combined_example(pos_only=1, standard=2, kwd_only=3)// 不能运行
4. 任意的参数列表
一般来说,这些 可变参数
将在形式参数列表的末尾,因为它们收集传递给函数的所有剩余输入参数。出现在 *args
参数之后的任何形式参数都是 ‘仅关键字参数’,也就是说它们只能作为关键字参数而不能是位置参数。:
>>> def concat(*args, sep="/"):
... return sep.join(args)
...
>>> concat("earth", "mars", "venus")
'earth/mars/venus'
>>> concat("earth", "mars", "venus", sep=".")
'earth.mars.venus'
5. 解包参数列表
当参数已经在列表或元组中但要为需要单独位置参数的函数调用解包时,会发生相反的情况。例如,内置的 range() 函数需要单独的 start 和 stop 参数。如果它们不能单独使用,可以使用 *
操作符 来编写函数调用以便从列表或元组中解包参数:
>>> list(range(3, 6)) # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> list(range(*args)) # call with arguments unpacked from a list
[3, 4, 5]
同样的方式,字典可使用 **
操作符 来提供关键字参数:
>>> 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)
-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
经验总结
类初始化时传递参数
(不推荐使用,但是用起来确实挺方便,所以也记录一下)
class Dog(object):
def __init__(self, **kwargs) -> None:
for key,value in kwargs.items():
setattr(self,key,value)
a = Dog(name="Woof", age=8)
print(a.age) # 8
print(a.name) # Woof