6.1 定义函数

6.1.1 传参

Code
def greet_user(username):
    """文档字符串(docstring)"""
    print(f"Hello,{username.title()}")

greet_user("lily")
Hello,Lily

6.1.2 形参(parameter)和实参(argument)

形参即函数完成任务所需要的信息,例如greet_user(username)中的username

实参即在调用call 函数时传递给函数的信息,例如greet_user("lily")中的"lily"

位置实参 关键字实参 默认值,在给形参指定默认值时,等号两边不要出现空格,函数调用中的关键字实参也遵循这种约定。

6.2 返回值

6.2.1 返回字典

实参可选

Code
def get_formatted_name(first_name, last_name, middle_name=''):
    """返回标准格式的姓名"""
    if middle_name: 
        full_name = f"{first_name} {middle_name} {last_name}"
    else: 
        full_name = f"{first_name} {last_name}" 
    return full_name.title() 

musician = get_formatted_name('jimi', 'hendrix') 
print(musician) 
musician = get_formatted_name('john', 'hooker', 'lee') 
print(musician)
Jimi Hendrix
John Lee Hooker
Code
def build_person(first_name,last_name,age=None):
    """ 返回字典,其中包含姓名或年龄"""
    person = {"first": first_name,"last":last_name}
    
    if age:
        person["age"] = age
    return person
musician = build_person('jimi', 'hendrix',27) 
print(musician) 
{'first': 'jimi', 'last': 'hendrix', 'age': 27}

6.3 传递列表

Code
# 函数
def print_models(unprinted_designs, completed_models): 
    """ 模拟打印每个设计,直到没有未打印的设计为止
    打印每个设计后,都将其移到列表 completed_models 中 """ 
    while unprinted_designs: 
        current_design = unprinted_designs.pop() 
        print(f"Printing model: {current_design}") 
        completed_models.append(current_design)
        
def show_completed_models(completed_models): 
    """显示打印好的所有模型""" 
    print("\nThe following models have been printed:") 
    for completed_model in completed_models: 
        print(completed_model) 

# 主程序
unprinted_designs = ['phone case', 'robot pendant', 'dodecahedron']
completed_models = [] 

print_models(unprinted_designs, completed_models) 
show_completed_models(completed_models)

unprinted_designs
completed_models

# 主程序 使用列表副本
unprinted_designs = ['phone case', 'robot pendant', 'dodecahedron']
completed_models = [] 

print_models(unprinted_designs[:], completed_models) 
show_completed_models(completed_models)

unprinted_designs
completed_models
Printing model: dodecahedron
Printing model: robot pendant
Printing model: phone case

The following models have been printed:
dodecahedron
robot pendant
phone case
Printing model: dodecahedron
Printing model: robot pendant
Printing model: phone case

The following models have been printed:
dodecahedron
robot pendant
phone case
['dodecahedron', 'robot pendant', 'phone case']

6.4 传递任意数量的实参

Code
def make_pizza(*toppings):
    """打印顾客点的所有配料"""
    print(toppings)
    return toppings
tps = make_pizza("qwe","asd","zxc")
('qwe', 'asd', 'zxc')

Python先匹配位置实参和关键字实参,再将剩余的实参匹配到最后一个形参。*toppings 中的星号 * 创建一个名为 toppings 的元组。

**user_info中的两个星号 ** 创建一个名为user_info的字典,接收任意数量的关键字实参

Code
def build_profile(first, last, **user_info):
    """创建一个字典,其中包含我们知道的有关用户的一切"""
    user_info['first_name'] = first 
    user_info['last_name'] = last 
    return user_info 

user_profile = build_profile('albert', 'einstein', location='princeton', field='physics') 
print(user_profile)
{'location': 'princeton', 'field': 'physics', 'first_name': 'albert', 'last_name': 'einstein'}

6.5 模块module

6.6 导入整个模块

import module_name
module_name.function_name()

6.7 使用as给模块指定别名

import module_name as mn
mn.function_name()

6.8 导入特定函数

from module_name import function_name
function_name()

6.9 使用as给函数指定别名

from module_name import function_name as fn
fn()

6.10 使用* 导入模块中使用函数

不建议,同名覆盖

from module_name import *