2020.07.14 Python 入门的 Day7
成就:函数及其模块化
- 以下是 Python 中很简单的一个函数及其调用。
def greet_user(): print("Hello!") # def 定义一个函数 greet_user() # 调用这个函数
- 通过给予函数形参,可给函数提供信息。
def greet_user(username): print("Hello, " + username.title() + "!") # username 是传递给函数的形参 greet_user('jesse')
- 当向函数传递多个参数时,要注意调用函数时两个参数的位置。
def describe_pet(animal_type, pet_name): print(" I have a " + animal_type + ".") print("My " + animal_type + "'s name is " + pet_name.title() + '.') # 函数包含两个形参 describe_pet('hamster', 'harry') describe_pet('dog', 'willie') # 注意位置实参的顺序 describe_pet(animal_type= 'hamster', pet_name= 'harry') describe_pet(pet_name= 'harry', animal_type= 'hamster') # 提供关键字实参可不必保证顺序一致
- 编写函数时,可给每个形参以默认值,当不提供实参时,其值就为默认值。
def describe_pet(pet_name, animal_type= 'dog'): print(" I have a " + animal_type + ".") print("My " + animal_type + "'s name is " + pet_name.title() + ".") # animal_type 的默认值为 'dog' describe_pet('whillie') describe_pet(pet_name= 'whillie') # 默认了 animal_type 的值为'dog'
- 注意,这里修改了形参的顺序。因为如果函数调用时只提供一个实参,那么这个实参应该传递给 pet_name,
- 而非 animal_type,因此要把 pet_type 放到第一个。
- 函数并非简单的显示输出,还可以返回值,理论上,返回值可以是任意类型。
def get_formatted_name(first_name, last_name): full_name = first_name + " " + last_name return full_name.title() # 返回一个字符串 musician = get_formatted_name('jimi', 'hendrix') print(musician)
- 有时候我们需要让实参变为可选的,就需要将可选的那个形参的默认值为空。
def Get_formatted_name(first_name, last_name, middle_name=''): # 并不是每个人都有中间名,因此 middle_name 是可选的,设为空字符串 if middle_name: full_name = first_name + " " + middle_name + " " + last_name else: full_name = first_name + ' ' + last_name return full_name.title() # 根据 middle_name 是否为空判断有没有输入中间名 musician = Get_formatted_name('jimi', 'hendrix') print(musician)
- 有时候向一个函数传递列表很有用,但不同的格式会不同的效果。
def print_models(unprinted_designs, completed_models): while unprinted_designs: current_design = unprinted_designs.pop() print("Printing model: " + current_design) completed_models.append(current_design) # 向 print_modelsa 传递两个列表 def show_completed_models(completed_models): print(" The following models have been printed:") for completed_model in completed_models: print(completed_model) # 向 show_completed 传递两个列表 unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron'] completed_models = [] print_models(unprinted_designs, completed_models) show_completed_models(completed_models) # 但这里要注意的是 # 经过函数的处理,原来的两个列表也发生了永久性的变化 # 不再是传递给函数之前的样子了
function_name(list_name[:]) # 如果在调用函数的时候用切片法创建一个列表的副本 # 那么原来的列表的值就不会被修改 # 例如: print_models(unprinted_designs, completed_models) # 函数运行结束后,unprinted_designs 的值就不会发生改变 # 而 completed_models 的值就会发生改变
- 有时候我们不知道函数需要接受多少个实参,但 Python 允许传递任意数量的实参。
def make_pizza(*toppings): print(toppings) # 用 * 标记的 toppings 表示一个元组,用来储存任意数量的实参 # 在 Python 内部,任意数量的实参都以元组的形式储存 make_pizza('pepperoni') make_pizza('mushrooms', 'green peppers', 'extra cheese')
- 在调用上述 Python 代码中的 toppings 里面的数据,要用元组的方法。
def make_pizza2(*toppings): print(" Making a pizza with the following toppings:") for topping in toppings: print("-" + topping) # 向调用元组一样调用 toppings
- 如果要让函数接受不同类型的实参,必须要把接纳任意数量实参的形参放到最后。
def make_pizza3(size, *toppings): print(" Making a " + str(size) + "-inch pizza with the following toppings:") for topping in toppings: print("- " + topping) # *toppings 在最后 make_pizza3(16, 'pepperoni') make_pizza3(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_info 表示一个能接纳任意数量的键—值对的字典 user_profile = build_profile('albert', 'einstein', location= 'princeton', field= 'physics') # 提供键值对的格式 键=值 print(user_profile)
- 函数的优点之一是可将他们的代码与主程序分离,称为模块化。
- 模块化的第一步是将函数储存在模块中。
# 这是一个名为 pizza.py 的文件 # 这个文件中只有定义一个函数的代码 def make_pizza(size, *toppings): print(" Making a " + str(size) + "-inch pizza with the following toppings:") for topping in toppings: print("- " + topping)
- 第二步是在其他程序中导入模块。
# 这是一个与 pizza.py 在同一个文件夹下的 .py 文件 import pizza # 这个语句会让 Python 打开 pizza.py 并将其中的所有函数导入到此程序 pizza.make_pizza(16, 'pepperoni') pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese') # 调用时要注意加上 pizza.
# 这是另一种导入方式 from pizza import make_pizza # 将 pizza.py 的函数 make_pizza 导入到此函数 make_pizza(16, 'pepperoni') make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese') # 调用时就不需要添加其他的前缀了
# 这是在导入的同时加上别名,用 as 语句 from pizza import make_pizza as mp mp(16, 'pepperoni') mp(12, 'mushrooms', 'green peppers', 'extra cheese')
import pizza as p # 这也是添加别名 p.make_pizza(16, 'pepperoni') p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
from pizza import * # 这个语句是将 pizza.py 中的所有函数都复制过来 make_pizza(16, 'pepperoni') make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese') # 调用时同样不需要加前缀