位置参数、关键字参数、默认值
def test_position_arg(arg1, arg2):
# 位置参数
print arg1, arg2
def test_key_arg(arg1=1, arg2=2):
# 关键字参数
print arg1, arg2
def test(arg1, arg2=2):
# arg2是默认参数
print arg1, arg2
# 两种调用方式都可以
test(1, 2)
test(arg2=22, arg1=11)
输出结果:
1 2
11 22
[Finished in 0.4s]
任意数量的参数,*args **kwargs
# *toppings这个形参,会接收调用语句的所有实参
# 星号让Python创建一个名为toppings的空元组,并将收到的所有值都封装到元组中
def make_pizze(*toppings):
"""打印顾客所点的所有配料
"""
print(toppings)
make_pizze('pepperoni')
make_pizze('pepperoni', "green peppers", "extra cheese")
代码输出:
('pepperoni', 'green peppers', 'extra cheese')
# 两个星号会让Python创建一个user_info的控制点,并将收到的所有键值对都放到字典中。
def build_profile(first, last, **user_info):
"""创建一个字典,存储用户信息
"""
user_info["first"] = first
user_info["last"] = last
return user_info
user_profile = build_profile('hong', "wang",
location="beijing",
field="computer")
print(user_profile)
代码输出:
{'location': 'beijing', 'field': 'computer', 'first': 'hong', 'last': 'wang'}