生成器与迭代器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# 迭代器 class Fibonacci: def __init__(self, n): self.a = 0 self.b = 1 self.count = 0 self.n = n def __iter__(self): return self def __next__(self): if self.count > self.n: raise StopIteration now = self.a self.a, self.b = self.b, self.a + self.b self.count += 1 return now # 生成器 def fibonacci(n): a, b, counter = 0, 1, 0 while True: if counter > n: return yield a a, b = b, a + b counter += 1 # 迭代器 f = Fibonacci(10) while True: try: print(next(f), end=" ") except StopIteration: print('\n') break # 生成器 f = fibonacci(0) while True: try: print(f.__next__(), end=" ") except StopIteration: break |
生成器进阶 - send
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
from itertools import count def func1(): a = yield 1 print(a) b = yield 2 print(b) c = yield 3 print(c) yield "done" func = func1() for i in count(): try: print(f"interaiton setp : {i},", f"answer = {func.__next__()}") except StopIteration: break func = func1() print(func.__next__()) print(func.send(4)) print(func.send(5)) print(func.send(6)) func.close() |
自定义错误类型
1 2 3 4 5 6 7 8 9 10 |
class NameTooShortError(Exception): pass def validate(name): if len(name) < 10: raise NameTooShortError(name) validate("321") |
修饰器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
def decorate_1(func): def inner1(*args): print('1', func.__name__, args) func(*args) return inner1 def decorate_2(func): def inner2(*args): print('2', func.__name__, args) func(*args) return inner2 @decorate_1 @decorate_2 def main(*args): print('test', args) main(1, 2, 3, 4) from functools import wraps def wrapper(func): @wraps(func) def inner_function(): pass return inner_function @wrapper def wrapped(): pass print(wrapped.__name__) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import time from functools import wraps def cal_time(unit='s'): def input_func(func): units = ['ms', 's', 'min', 'hour', 'day'] times = [1000, 1, 1 / 60, 1 / 3600, 1 / 3600 / 24] if unit.lower() not in units: raise TypeError(unit) time_process = times[units.index(unit)] @wraps(func) def wrap(*args, **kwargs): begin_time = time.time() ans = func(*args, **kwargs) print(func.__name__, f"用时 {(time.time() - begin_time) * time_process}") return ans return wrap return input_func |
常见修饰器
1 2 3 4 5 6 7 8 9 10 11 12 |
# 无需实例化对象,无需self,需要cls @classmethod # 无需实例化对象,无需self和cls @staticmethod import functools # 缓存结果,算法上可用 @functools.cache # 自定义修饰器时使用 @functools.wraps # 特定代码替换解释器加快代码运行速度 from numba import jit @jit |
海象运算符:=(python>=3.8)
1 2 3 4 |
# 简单来说就是简化代码,使用更方便,需要注意运算优先级 # 下列代码需要加括号才能使 n = len(a) if (n := len(a)) > 10: print(f"List is too long ({n} elements, expected <= 10)") |
特殊的list deque
因为最近在写算法题,用的是C++,看了下python也有deque
1 2 |
from collections import deque d=deque() |
拓扑算法库
1 |
from graphlib import TopologicalSorter |
collections库
1 2 3 |
""" https://blog.csdn.net/StarSky_Ye/article/details/119272313 """ |
下划线(_)的作用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# codeTest.py _a = "_a" a = "a" def _test_underline(): print("_test_underline") def test_underline(): print("test_underline") # code.py from codeTest import * test_underline() # _test_underline() # ↑报错 print(a) # print(_a) # ↑报错 |
1 2 |
# 初始化数组 matrix = [0 for _ in range(10)] |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class A: __private_var = 1000 def __init__(self) -> None: self.__private_var2 = 2000 self.var3 = 3000 self.__print("A.__print") def __print(self, x): print(x) a = A() print(a.var3) # print(a.__private_var2) # ↑报错 # print(a.__print("x")) # ↑报错 |