python学习笔记:第八章 函数(二)

󰃭 2017-04-23

python学习笔记:第八章 函数(二)


传递任意数量的实参

接纳任意数量实参的形参放在最后

def make_pizza(size, *toppings):
    print("\nMaking a " + str(size) +"-inch pizza with the following toppings:")
    for topping in toppings:
        print("- " + topping)
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

使用任意数量的关键字实参

def build_profile(first, last, **user_info):
    profile = {}
    profile['first_name'] = first
    profile['last_name'] = last
    for key, value in user_info.items():
        profile[key] = value
    return profile

user_profile = build_profile('albert', 'einsterin',
                             location = 'princeton',
                             field = 'physics')
print(user_profile)

将函数存储在模块中

函数存储为:pizza.py

def make_pizza(size, *toppings):
    print("\nMaking a " + str(size) +
          "-inch pizza with the following toppings:")
    for topping in toppings:
        print("- " + topping)

调用函数: pizza.py

import pizza

pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

导入特定的函数

from pizza import make_pizza
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushroom', 'green peppers', 'extra cheese')

使用as给函数指定别名

from pizza import make_pizza as mp
mp(16, 'pepperoni')
mp(12, 'mushrooms', 'green peppers', 'extra cheese')

使用as给模块指定别名

import pizza as p
p.make_pizza(16, 'pepperoni')
p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

导入模块中的所有函数

from pizza import *

函数编写指南

给形参指定默认值时,等号两边不要有空格

函数调用中的关键字实参,也遵循这种约定

def function_name(parameter_0, parameter_1='default value')
function_name(value_0, parameter_1='value')