【脚本语言系列】关于Python基础知识魔法变量,你需要知道的事

如何使用魔法变量

  • *args/*var
# -*- coding:utf-8 -*-
# common name: *args
def greet(the_arg, *args):
    print "First normal arg:",the_arg
    for arg in args:
        print "another arg through *args: ",arg

greet("This is AllenMoore.")    

# difference name: *vars
def greet(the_arg, *vars):
    print "First normal arg:",the_arg
    for arg in vars:
        print "another arg through *args: ",arg

greet("This is AllenMoore.")  
First normal arg: This is AllenMoore.
First normal arg: This is AllenMoore.
# -*- coding:utf-8 -*-
# common samples
def greet_samples(arg1, arg2, arg3):
    print "arg1: ", arg1
    print "arg2: ", arg2
    print "arg3: ", arg3

greet_samples(123, "123321", 321)

print "\n"

# *args samples
args = (321, "321123", 123)
greet_samples(*args)
arg1:  123
arg2:  123321
arg3:  321


arg1:  321
arg2:  321123
arg3:  123
  • **kwargs/**vars
# -*- coding:utf-8 -*-
# common name: **kwargs
def greet(**kwargs):
    for key, value in kwargs.items():
        print "{0} == {1}".format(key, value)

greet(name="AllenMoore")

# difference name: **vars
def greet(**vars):
    for key, value in vars.items():
        print "{0} == {1}".format(key, value)

greet(name="AllenMoore")
name == AllenMoore
name == AllenMoore
# -*- coding:utf-8 -*-
# common samples
def greet_samples(arg1, arg2, arg3):
    print "arg1: ", arg1
    print "arg2: ", arg2
    print "arg3: ", arg3

greet_samples(123, "123321", 321)

print "\n"

# *args samples
kwargs = {"arg3":123, "arg2":"321123", "arg1":321}
greet_samples(**kwargs)
arg1:  123
arg2:  123321
arg3:  321


arg1:  321
arg2:  321123
arg3:  123

什么是魔法变量

*args非键值对的可变数量的参数列表
**kwargs键值对的可变数量的参数列表
some_func(fargs, *args, **kwargs)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值