如何使用魔法变量
- *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)