Python的魔法变量

1. 写在前面

首先需要说明的是,星号及星号的个数是必须的,而后面的变量名确实可以任意选取的。

2. *args

*args表示的是整合或解构可变长度的列表或元组,它的用法可以用于定义函数时的形参或者调用函数的实参。两种用法刚好互逆

2.1 作为定义函数的形参

当*args作为定义函数时的形参进行使用的时候,其作用是将实参传过来的多个位置参数整合为一个可迭代的元组类型。

def test_var_args(f_arg, *argv):
    print("first normal arg:", f_arg)
    print(type(argv))
    for arg in argv:
        print("another arg through *argv:", arg)
test_var_args('yasoob', 'python', 'eggs', 'test')
>>[output:]
first normal arg: yasoob
<class 'tuple'>
another arg through *argv: python
another arg through *argv: eggs
another arg through *argv: test

整合或解构是我自己的理解:

这里我需要说明一点的就是,为什么我要加上整合或解构呢?
下面这个栗子告诉了我们在形参的时候,*args并没有起到解构的作用!

def test_var_args(f_arg, *argv):
    print("first normal arg:", f_arg)
    print(type(argv))
    for arg in argv:
        print("another arg through *argv:", arg)
test_var_args('yasoob', ('python', 'eggs', 'test'))
>>
first normal arg: yasoob
<class 'tuple'>
another arg through *argv: ('python', 'eggs', 'test')
2.2 作为调用函数的实参

当*args作为调用函数的实参进行使用的时候,其作用是将原有的列表和数组解构为多个实参。

def test_args_kwargs(arg1, arg2, arg3):
    print("arg1:", arg1)
    print("arg2:", arg2)
    print("arg3:", arg3)
args = ("two", 3, 5)
test_args_kwargs(*args)
>>
arg1: two
arg2: (3, 5)
arg3: 5
3. **kwargs

*args表示的是整合或解构可变长度的键值对,它的用法可以用于定义函数时的形参或者调用函数的实参。两种用法也刚好互逆

3.1 作为定义函数的形参

当 **kwargs作为定义函数时的形参进行使用的时候,其作用是将实参传过来的多个关键字参数整合为一个可迭代的字典类型。

def greet_me(**kwargs):
    print(type(kwargs))
    for key, value in kwargs.items():
        print("{0} == {1}".format(key, value))
greet_me(name="yasoob", cls=5)
>>
<class 'dict'>
name == yasoob
cls == 5
3.2 作为调用函数的实参

当 **kwargs作为调用函数的实参进行使用的时候,其作用是将原有的字典变量解构为多个关键字类型的实参。

def test_args_kwargs(arg1, arg2, arg3):
    print("arg1:", arg1)
    print("arg2:", arg2)
    print("arg3:", arg3)
kwargs = {"arg3": 3, "arg2": "two", "arg1": 5}
test_args_kwargs(**kwargs)
>>
arg1: 5
arg2: two
arg3: 3
4. *args与**kwargs的调用顺序

标准参数,位置参数,关键字参数;因为位置参数在关键字参数的前面,所以 *args 必须放在 **kwargs 的前面。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值