gotour

概念 包 go从main包开始运行 声明包 package main 导入包 通常你不需要自己导入包,写代码时编辑器会帮你导入 import "fmt" import ( "fmt" "math" ) 导出名 导入一个包时只能使用其中已导出的导出名 当一个导出名以大写字母开头,那么这个导出名就是已导出的 语法 方法 定义方法 必须定义入参类型和返回类型。 长得和py中的类似,方法要用开头小写的驼峰来命名 func myFn(add1 int, add2 int) int { return add2 + add1 } 便捷写法 如果参数的类型相同,并且挨在一起,那么可以这样写 func myFn1(add1, add2 int) int { return add2 + add1 } 多个返回值 声明多个返回值使用(type1, type2),接收多个返回值要使用:= func sw(s1, s2 string) (string, string) { return s2, s1 } func main() { a, b := sw("hello", "world") t, _ := sw("hello", "world") fmt.Print(t) fmt.Println(a, b) } 如果你只想接收一个,也必须使用:=,不想保存的参数使用_接收 更快捷的返回 使用变量名进行返回 func split(sum int) (x, y int) { x = sum * 4 / 9 y = sum - x return } 变量 无论使用var xx type显式的表示还是自动推导,一个变量是必须有类型的。 定义 使用var来定义变量 var abc = "abc" fmt.Println(abc) 如果你在方法内定义了变量,那么必须要使用它 批量初始化 var a, b, c = 'A', 'B', 'c' fmt.Println(a, b, c) 带类型的变量 var a string a = "string" fmt.Println(a) 简短的声明 使用:=做类型推导 ...

2026-04-03 · 2 分钟 · ziwindlu · 源笔记:02-Knowledge/编程/gotour.md

Python

语言规范 python之禅 pythonic 命名 语法 数据 变量定义 作用域 数据结构 运算 流程控制 条件 循环 函数 定义 调用 常用函数 map filter range enumerate 导包 import util as u from util.file_util import read_lines from util.log_util import * 异常处理 AOP python_aop 多线程 多线程&多进程 由于GIL(全局解释器锁),Python多线程无法真正并行(仅并发)。 多进程可绕过GIL,实现真正的并行(利用多核CPU)。 多进程: import os from multiprocessing import Process def process_task(name): print(f"子进程 {name} PID: {os.getpid()},父进程 PID: {os.getppid()}") if __name__ == '__main__': p = Process(target=process_task, args=('child',)) p.start() p.join() print(f"主进程 PID: {os.getpid()}") 进程池 from mulitprocessing import Pool from multiprocessing import Process, Lock import time def process_task(lock, filepath): with lock: # 进程间文件访问需要锁 with open(filepath, 'a') as f: f.write(f"Process {os.getpid()} wrote at {time.time()}\n") if __name__ == '__main__': lock = Lock() # 跨进程锁 filepath = 'shared.log' processes = [Process(target=process_task, args=(lock, filepath)) for _ in range(3)] for p in processes: p.start() for p in processes: p.join() 多线程 import threading def thread_task(name): print(f"线程 {name} 正在执行") threads = [] for i in range(3): t = threading.Thread(target=thread_task, args=(f'Thread-{i}',)) threads.append(t) t.start() for t in threads: t.join() 线程池 from concurrent.futures import ThreadPoolExecutor import requests def fetch_url(url): response = requests.get(url) return f"{url}: {len(response.content)} bytes" urls = ["https://www.python.org", "https://www.google.com", "https://www.github.com"] # 使用线程池(适合I/O阻塞操作) with ThreadPoolExecutor(max_workers=3) as executor: results = list(executor.map(fetch_url, urls)) print(results) 锁仅针对于多线程 import threading counter = 0 lock = threading.Lock() def increment(): global counter for _ in range(100000): with lock: # 自动获取和释放锁 counter += 1 threads = [threading.Thread(target=increment) for _ in range(5)] for t in threads: t.start() for t in threads: t.join() print(f"最终计数器值: {counter}") # 应该是500000 文件操作 with open('.bashrc', 'r', encoding='utf-8') as f: f.readlines() f.wirtelines() 网络编程 数据库相关 redis import redis # 连接 pool = redis.ConnectionPool(host='localhost', port=6379, db=0) r = redis.Redis(connection_pool=pool) # 操作 r.set('visits', 0) r.incr('visits') print(f"Total visits: {r.get('visits').decode()}") mysql SQLAlchemy ...

2026-04-03 · 2 分钟 · ziwindlu · 源笔记:02-Knowledge/编程/Python.md

python_aop

前置知识 切面(Aspect): 封装横切关注点的模块 连接点(Join Point): 程序执行过程中的特定点(如方法调用) 通知(Advice): 在连接点执行的动作(如方法执行前后) 切入点(Pointcut): 定义哪些连接点会被通知影响 一般写法 装饰器 def log_aspect(func): def wrapper(*args, **kwargs): print(f"开始执行: {func.__name__}") result = func(*args, **kwargs) print(f"结束执行: {func.__name__}") return result return wrapper @log_aspect def business_method(): print("执行业务逻辑...") business_method() 使用类装饰器 class TransactionAspect: def __init__(self, func): self.func = func def __call__(self, *args, **kwargs): print("开启事务") try: result = self.func(*args, **kwargs) print("提交事务") return result except Exception as e: print("回滚事务") raise e @TransactionAspect def process_order(): print("处理订单业务...") process_order() 使用上下文管理器 class PerformanceAspect: def __enter__(self): self.start = time.time() def __exit__(self, exc_type, exc_val, exc_tb): print(f"耗时: {time.time() - self.start:.4f}秒") def business_logic(): with PerformanceAspect(): print("执行业务逻辑...") time.sleep(1) business_logic()

2026-04-03 · 1 分钟 · ziwindlu · 源笔记:02-Knowledge/编程/python_aop.md