高级用法

枚举

from enum import Enum

class VIP(Enum):
  yellow = 1
  blue = 2
  green = 3
  red = 4

print(VIP.red) # VIP.red

# 获取枚举值
print(VIP.red.value) # 4

# 值转类型
VIP(2) # VIP.blue

# 枚举遍历
for v in VIP:
  print(v)

闭包

def outer():
  t = 0
  def inner(n):
    nonlocal t # 定义使用外层变量 # global 定义使用全局变量
    t = t + n
    return t
  return inner

fn = outer()
print(fn(1)) # 1
print(fn(4)) # 5
print(fn(5)) # 10

匿名函数

def add(x, y):
  return x + y

add2 = lambda x, y: x + y
print(add2(2, 3)) # 5

三元表达式

def check(x, y):
  # 真的结果 if 条件判断 else 假的结果
  a = x if x > y else y
  return a

map 递归

user_list = [1,2,3,4]
res = map(lambda x: x * x, user_list)
print(list(res)) # [1, 4, 9, 16]

reduce 累加器

from functools import reduce

user_list = [1,2,3,4]
res = reduce(lambda x, y: x + y, user_list, 0)
print(res) # 10

filter 过滤

user_list = [1,2,3,4,5,6,7]
res = filter(lambda x: True if x > 3 else False, user_list)
print(list(res)) # [4, 5, 6, 7]

装饰器

import time

def decorator(func):
  def wrapper(*args, **kw):
    print('timestamp:', time.time())
    func(*args, **kw) # 需要处理 可变参数 和 可变关键字参数 的情况
  return wrapper

@decorator
def fun1():
  print('this is fun1')

fun1()