# 一个简单的函数

def exmaple(required_arg):
print required_arg

exmaple("Hello, World!")

>> Hello, World!

exmaple("Hello, World!", "another string")

>> TypeError: exmaple() takes exactly 1 argument (2 given)

# 定义函数时，使用*arg和**kwarg

*arg和**kwarg 可以帮助我们处理上面这种情况，允许我们在调用函数的时候传入多个实参

def exmaple2(required_arg, *arg, **kwarg):
if arg:
print "arg: ", arg

if kwarg:
print "kwarg: ", kwarg

exmaple2("Hi", 1, 2, 3, keyword1 = "bar", keyword2 = "foo")

>> arg:  (1, 2, 3)
>> kwarg:  {'keyword2': 'foo', 'keyword1': 'bar'}

• *arg会把多出来的位置参数转化为tuple
• **kwarg会把关键字参数转化为dict

def sum(*arg):
res = 0
for e in arg:
res += e
return res

print sum(1, 2, 3, 4)
print sum(1, 1)
>> 10
>> 2

def person(required_arg, *, keyword1, keyword2):
print(required_arg, keyword1, keyword2)

person("Hi", keyword1="bar", keyword2="foo")
>> Hi bar foo

person("Hi", "bar", "foo")

>> TypeError: person() takes 1 positional argument but 3 were given

# 调用函数时使用*arg和**kwarg

def sum(a, b, c):
return a + b + c

a = [1, 2, 3]

# the * unpack list a
print sum(*a)
>> 6
def sum(a, b, c):
return a + b + c

a = {'a': 1, 'b': 2, 'c': 3}

# the ** unpack dict a
print sum(**a)
>> 6