• 函数可以赋值给变量
      • 函数可以作为函数的参数
      • 函数可以作为函数的返回值
    • 高阶函数的用法(、map以及它们的替代品)

    • 位置参数、可变参数、关键字参数、命名关键字参数

    • 参数的元信息(代码可读性问题)

    • 匿名函数和内联函数的用法(lambda函数)

    • 闭包和作用域问题

      • globalnonlocal关键字的作用

        global:声明或定义全局变量(要么直接使用现有的全局作用域的变量,要么定义一个变量放到全局作用域)。

        nonlocal:声明使用嵌套作用域的变量(嵌套作用域必须存在该变量,否则报错)。

    • 装饰器函数(使用装饰器和取消装饰器)

      例子:输出函数执行时间的装饰器。

      1. def record_time(func):
      2. """自定义装饰函数的装饰器"""
      3. @wraps(func)
      4. def wrapper(*args, **kwargs):
      5. start = time()
      6. result = func(*args, **kwargs)
      7. print(f'{func.__name__}: {time() - start}秒')
      8. return wrapper

      ```Python from functools import wraps from time import time

    def record(output): “””可以参数化的装饰器”””

    1. ```Python
    2. from time import time
    3. class Record():
    4. """通过定义类的方式定义装饰器"""
    5. def __init__(self, output):
    6. self.output = output
    7. def __call__(self, func):
    8. @wraps(func)
    9. def wrapper(*args, **kwargs):
    10. start = time()
    11. result = func(*args, **kwargs)
    12. return result
    13. return wrapper

    例子:用装饰器来实现单例模式。

    1. from threading import RLock
    2. def singleton(cls):
    3. """线程安全的单例装饰器"""
    4. instances = {}
    5. locker = RLock()
    6. @wraps(cls)
    7. def wrapper(*args, **kwargs):
    8. if cls not in instances:
    9. with locker:
    10. if cls not in instances:
    11. instances[cls] = cls(*args, **kwargs)
    12. return instances[cls]