传递任意数量的实参

形参前加一个 * ,Python会创建一个已形参为名的空元组,将所有收到的值都放到这个元组中: 

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


make_pizza('pepperoni')
make_pizza('mushroom', 'green peppers', 'extra cheese')

不管函数收到多少实参,这种语法都管用。

1. 结合使用位置实参和任意数量实参

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, 'mushroom', 'green peppers', 'extra cheese')

运行结果:

Making a 16-inch pizza with the following toppings: 
- pepperoni

Making a 12-inch pizza with the following toppings: 
- mushroom
- green peppers
- extra cheese

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

def build_profile(first, last, **user_info):
    profile = dict()
    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', 'einstein', location='princeton', field='physic')
print(user_profile)

形参**user_info中的两个星号让python创建了一个名为user_info的空字典。

将函数存储在模块中

        将函数存储在称为模块的独立文件中,使用时再将模块导入到主程序中。目的:1. 隐藏程序代码细节;2.重用函数;3.与其他程序员共享这些文件;4.使用其他程序员编写的函数库。

1. 导入整个模块

pizza.py

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

 

making_pizzas.py

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

 即可以使用一下的语法来导入模块并使用模块中的任意函数:

import module_name
module_name.function_name( )

2. 导入特定的函数

from module_name import function_name    # 导入模块中一个函数
from module_name import function_0, function_1,,,    # 导入模块中的多个函数

eg:

making_pizzas.py

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

 导入的是函数,调用函数时就无需使用句点。

3. 使用as给函数指定别名

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

给函数指定别名的通用语法:

from modul_name import function_name as fn

4. 使用as给模块指定别名

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

给模块指定别名的通用语法:

import module_name as mn

5. 导入模块中的所有函数

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

导入所有函数的通用语法:

from module_name import *

函数编写指南

1. 函数命名和模块命名:指定描述性名称,且在只其中使用小写字母和下划线。

2. 函数定义后应紧跟注释,用以简要阐述改函数的功能,采用文档字符串格式。

3. 给形参指定默认值和函数调用中的关键字实参,等号两边不用空格。

4.所有程序或者模块包含多个函数时,使用两个空行将相邻的两个函数分开。

5. 所有import语句放在文件开头,唯一例外就是文件开头使用了注释来描述整个程序。