这次我要弄明白*arg、**kargs、/ 和 *

官网摘录

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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值