【python】速通筆記

Python學習路徑 - 從零基礎到入門

環境搭建

  1. 安裝Python

    • Windows: 從官網下載安裝包 https://www.python.org/downloads/
    • Mac/Linux: 通常已預裝,可通過終端輸入python3 --version檢查
  2. 配置開發環境

    • 推薦使用VS Code或PyCharm作為代碼編輯器
    • 安裝Python擴展插件
    • 創建第一個Python文件hello.py
      # hello.py
      print("Hello, Python!")
      
    • 運行程序: 在終端輸入python3 hello.py

基礎語法

  1. 變量與數據類型

    • 數字類型
      # 整數
      age = 20
      # 浮點數
      price = 3.99
      
    • 字符串
      name = "Alice"
      greeting = 'Hello, World!'
      
    • 布爾值
      is_student = True
      is_teacher = False
      
  2. 基本運算

    # 算術運算
    print(10 + 3)  # 13
    print(10 - 3)  # 7
    print(10 * 3)  # 30
    print(10 / 3)  # 3.333...# 字符串拼接
    first_name = "John"
    last_name = "Doe"
    full_name = first_name + " " + last_name
    print(full_name)  # John Doe
    
  3. 練習題目

    • 練習1: 計算兩個數的和
      num1 = 5
      num2 = 7
      # 計算并打印它們的和
      
    • 練習2: 打印個人信息
      name = "你的名字"
      age = 你的年齡
      # 打印"我叫XX,今年XX歲"
      

基礎語法

  1. 變量與數據類型

    • 數字、字符串、布爾值
      # 示例
      num = 42
      name = "Python"
      is_true = True
      
    • 列表、元組、字典、集合
      # 示例
      my_list = [1, 2, 3]
      my_tuple = (1, 2, 3)
      my_dict = {"name": "Alice", "age": 25}
      my_set = {1, 2, 3}
      
  2. 運算符

    • 算術運算符
      # 示例
      print(10 + 3)  # 13
      print(10 - 3)  # 7
      print(10 * 3)  # 30
      print(10 / 3)  # 3.333...
      print(10 // 3) # 3 (整除)
      print(10 % 3)  # 1 (取余)
      print(10 ** 3) # 1000 (冪)
      
    • 比較運算符
      # 示例
      print(10 > 3)  # True
      print(10 < 3)  # False
      print(10 == 3) # False
      print(10 != 3) # True
      
    • 邏輯運算符
      # 示例
      print(True and False)  # False
      print(True or False)   # True
      print(not True)        # False
      
  3. 控制結構

    • 條件語句(if/elif/else)
      # 示例
      age = 18
      if age < 13:print("兒童")
      elif age < 18:print("青少年")
      else:print("成人")
      
    • 循環(for/while)
      # for循環示例
      for i in range(5):print(i)# while循環示例
      count = 0
      while count < 5:print(count)count += 1
      
    • break和continue
      # 示例
      for i in range(10):if i == 5:break  # 退出循環if i % 2 == 0:continue  # 跳過本次循環print(i)
      

函數編程

  1. 函數定義與調用
    # 示例
    def greet(name):"""打印問候語"""print(f"Hello, {name}!")greet("Alice")  # 調用函數
    
  2. 參數傳遞
    • 位置參數
      # 示例
      def add(a, b):return a + bprint(add(3, 5))  # 8
      
    • 關鍵字參數
      # 示例
      def greet(name, message):print(f"{message}, {name}!")greet(message="Hi", name="Bob")  # Hi, Bob!
      
    • 默認參數
      # 示例
      def greet(name, message="Hello"):print(f"{message}, {name}!")greet("Alice")  # Hello, Alice!
      greet("Bob", "Hi")  # Hi, Bob!
      
    • 可變參數(*args, **kwargs)
      # 示例
      def print_args(*args):for arg in args:print(arg)print_args(1, 2, 3)  # 打印1, 2, 3def print_kwargs(**kwargs):for key, value in kwargs.items():print(f"{key}: {value}")print_kwargs(name="Alice", age=25)  # 打印name: Alice, age: 25
      
  3. lambda表達式
    # 示例
    square = lambda x: x ** 2
    print(square(5))  # 25# 與map/filter一起使用
    numbers = [1, 2, 3, 4]
    squared = list(map(lambda x: x**2, numbers))
    print(squared)  # [1, 4, 9, 16]
    
  4. 作用域與閉包
    # 作用域示例
    x = 10  # 全局變量def foo():y = 20  # 局部變量print(x + y)  # 可以訪問全局變量foo()  # 30# 閉包示例
    def outer_func(x):def inner_func(y):return x + yreturn inner_funcclosure = outer_func(10)
    print(closure(5))  # 15
    

面向對象編程

  1. 類與對象
    # 示例
    class Dog:# 類屬性species = "Canis familiaris"# 初始化方法def __init__(self, name, age):self.name = name  # 實例屬性self.age = age# 實例方法def description(self):return f"{self.name} is {self.age} years old"# 實例方法def speak(self, sound):return f"{self.name} says {sound}"# 創建對象
    my_dog = Dog("Buddy", 5)
    print(my_dog.description())  # Buddy is 5 years old
    print(my_dog.speak("Woof"))  # Buddy says Woof
    
  2. 繼承與多態
    # 繼承示例
    class Bulldog(Dog):def speak(self, sound="Woof"):return super().speak(sound)# 多態示例
    def animal_speak(animal):print(animal.speak())bulldog = Bulldog("Max", 3)
    print(bulldog.speak())  # Max says Woof
    
  3. 魔術方法
    # __str__ 示例
    class Dog:def __init__(self, name, age):self.name = nameself.age = agedef __str__(self):return f"Dog(name='{self.name}', age={self.age})"my_dog = Dog("Buddy", 5)
    print(my_dog)  # Dog(name='Buddy', age=5)# __add__ 示例
    class Vector:def __init__(self, x, y):self.x = xself.y = ydef __add__(self, other):return Vector(self.x + other.x, self.y + other.y)v1 = Vector(1, 2)
    v2 = Vector(3, 4)
    v3 = v1 + v2
    print(v3.x, v3.y)  # 4 6
    
  4. 裝飾器
    # 函數裝飾器示例
    def my_decorator(func):def wrapper():print("裝飾器: 調用函數前")func()print("裝飾器: 調用函數后")return wrapper@my_decorator
    def say_hello():print("Hello!")say_hello()
    # 輸出:
    # 裝飾器: 調用函數前
    # Hello!
    # 裝飾器: 調用函數后# 類裝飾器示例
    def class_decorator(cls):class Wrapper:def __init__(self, *args, **kwargs):self.wrapped = cls(*args, **kwargs)def __getattr__(self, name):return getattr(self.wrapped, name)return Wrapper@class_decorator
    class MyClass:def __init__(self, value):self.value = valuedef show(self):print(f"Value: {self.value}")obj = MyClass(42)
    obj.show()  # Value: 42
    

高級特性

  1. 生成器與迭代器

    # 生成器示例
    def count_up_to(max):count = 1while count <= max:yield countcount += 1counter = count_up_to(5)
    print(next(counter))  # 1
    print(next(counter))  # 2# 迭代器示例
    my_list = [1, 2, 3]
    my_iter = iter(my_list)
    print(next(my_iter))  # 1
    print(next(my_iter))  # 2
    
  2. 裝飾器高級用法

    # 帶參數的裝飾器
    def repeat(num_times):def decorator_repeat(func):def wrapper(*args, **kwargs):for _ in range(num_times):result = func(*args, **kwargs)return resultreturn wrapperreturn decorator_repeat@repeat(num_times=3)
    def greet(name):print(f"Hello {name}")greet("Alice")# 類裝飾器
    class Timer:def __init__(self, func):self.func = funcdef __call__(self, *args, **kwargs):import timestart = time.time()result = self.func(*args, **kwargs)end = time.time()print(f"執行時間: {end - start:.2f}秒")return result@Timer
    def long_running_func():time.sleep(2)long_running_func()
    
  3. 元類編程

    # 元類示例
    class Meta(type):def __new__(cls, name, bases, namespace):namespace['version'] = '1.0'return super().__new__(cls, name, bases, namespace)class MyClass(metaclass=Meta):passprint(MyClass.version)  # 1.0# 動態創建類
    def make_class(name):return type(name, (), {'x': 10})DynamicClass = make_class('DynamicClass')
    print(DynamicClass().x)  # 10
    
  4. 上下文管理器

    # with語句示例
    with open('file.txt', 'w') as f:f.write('Hello, world!')# 自定義上下文管理器
    class MyContextManager:def __enter__(self):print("進入上下文")return selfdef __exit__(self, exc_type, exc_val, exc_tb):print("退出上下文")with MyContextManager() as cm:print("在上下文中")
    
  5. 多線程與多進程

    # 多線程示例
    import threadingdef worker():print("線程執行")threads = []
    for i in range(5):t = threading.Thread(target=worker)threads.append(t)t.start()for t in threads:t.join()# 多進程示例
    from multiprocessing import Processdef worker():print("進程執行")processes = []
    for i in range(5):p = Process(target=worker)processes.append(p)p.start()for p in processes:p.join()
    
  6. 異步編程(asyncio)

    import asyncioasync def hello():print("Hello")await asyncio.sleep(1)print("World")async def main():await asyncio.gather(hello(), hello(), hello())asyncio.run(main())
    

常用標準庫

  1. os/sys - 系統操作

    # os示例
    import os
    print(os.getcwd())  # 獲取當前工作目錄
    os.mkdir('new_dir')  # 創建目錄# sys示例
    import sys
    print(sys.argv)  # 命令行參數
    sys.exit(0)  # 退出程序
    
  2. pathlib - 現代化路徑操作

    from pathlib import Path# 創建路徑對象
    p = Path('.')# 遍歷目錄
    for f in p.glob('*.py'):print(f.name)# 路徑拼接
    new_file = p / 'subdir' / 'new_file.txt'
    new_file.write_text('Hello, Pathlib!')
    
  3. subprocess - 運行外部命令

    import subprocess# 運行簡單命令
    result = subprocess.run(['ls', '-l'], capture_output=True, text=True)
    print(result.stdout)# 管道操作
    ps = subprocess.Popen(['ps', '-aux'], stdout=subprocess.PIPE)
    grep = subprocess.Popen(['grep', 'python'], stdin=ps.stdout, stdout=subprocess.PIPE)
    ps.stdout.close()
    output = grep.communicate()[0]
    print(output.decode())
    
  4. re - 正則表達式

    import re# 匹配示例
    pattern = r'\b\w+\b'
    text = 'Hello, world!'
    matches = re.findall(pattern, text)
    print(matches)  # ['Hello', 'world']# 替換示例
    new_text = re.sub(r'world', 'Python', text)
    print(new_text)  # Hello, Python!
    
  5. datetime - 日期時間

    from datetime import datetime, timedelta# 當前時間
    now = datetime.now()
    print(now.strftime('%Y-%m-%d %H:%M:%S'))  # 格式化輸出# 時間計算
    tomorrow = now + timedelta(days=1)
    print(tomorrow)
    
  6. json - JSON處理

    import json# 序列化
    data = {'name': 'Alice', 'age': 25}
    json_str = json.dumps(data)
    print(json_str)  # {"name": "Alice", "age": 25}# 反序列化
    loaded_data = json.loads(json_str)
    print(loaded_data['name'])  # Alice
    
  7. collections - 高級數據結構

    from collections import defaultdict, Counter, namedtuple# defaultdict示例
    d = defaultdict(int)
    d['a'] += 1
    print(d['a'])  # 1# Counter示例
    cnt = Counter('abracadabra')
    print(cnt.most_common(3))  # [('a', 5), ('b', 2), ('r', 2)]# namedtuple示例
    Point = namedtuple('Point', ['x', 'y'])
    p = Point(11, y=22)
    print(p.x + p.y)  # 33
    

學習資源

  1. 官方文檔: https://docs.python.org/3/
  2. 推薦書籍:
    • 《Python編程:從入門到實踐》- 適合初學者
    • 《流暢的Python》- 適合進階學習
    • 《Python Cookbook》- 實用技巧
  3. 練習平臺:
    • LeetCode: 算法練習
    • Codewars: 編程挑戰
    • HackerRank: 綜合練習
  4. 在線課程:
    • Coursera: Python專項課程
    • Udemy: 實用Python項目
  5. 社區資源:
    • Stack Overflow: 問題解答
    • GitHub: 開源項目學習
    • Python官方論壇

進階主題

  1. 并發編程

    # 線程池示例
    from concurrent.futures import ThreadPoolExecutordef task(n):return n * nwith ThreadPoolExecutor(max_workers=4) as executor:results = executor.map(task, range(10))print(list(results))
    
  2. 性能優化

    # 使用timeit測量代碼執行時間
    import timeitsetup = """
    def sum_range(n):return sum(range(n))
    """print(timeit.timeit('sum_range(1000)', setup=setup, number=1000))
    
  3. 設計模式

    # 單例模式實現
    class Singleton:_instance = Nonedef __new__(cls):if cls._instance is None:cls._instance = super().__new__(cls)return cls._instances1 = Singleton()
    s2 = Singleton()
    print(s1 is s2)  # True
    

實戰項目

1. 電商數據分析系統

需求分析:

  • 從CSV文件讀取銷售數據
  • 計算每日/每月銷售額
  • 生成可視化報表

實現步驟:

import pandas as pd
import matplotlib.pyplot as pltdef sales_analysis():# 1. 讀取數據df = pd.read_csv('sales.csv')# 2. 數據處理df['date'] = pd.to_datetime(df['date'])daily_sales = df.groupby(df['date'].dt.date)['amount'].sum()# 3. 可視化plt.figure(figsize=(10,6))daily_sales.plot(kind='bar')plt.title('每日銷售額')plt.savefig('daily_sales.png')

調試技巧:

  • 使用df.head()檢查數據讀取是否正確
  • 打印中間結果驗證數據處理邏輯

2. 天氣查詢應用

需求分析:

  • 調用天氣API獲取實時數據
  • 支持多城市查詢
  • 緩存歷史查詢記錄

實現步驟:

import requests
import jsonclass WeatherApp:def __init__(self, api_key):self.api_key = api_keyself.history = {}def get_weather(self, city):url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={self.api_key}"response = requests.get(url)data = json.loads(response.text)self.history[city] = datareturn data

調試技巧:

  • 檢查API響應狀態碼
  • 使用try-except處理網絡異常

3. 機器學習房價預測

需求分析:

  • 使用線性回歸模型
  • 評估模型性能
  • 部署預測接口

實現步驟:

from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split# 加載數據
data = pd.read_csv('housing.csv')
X = data[['size', 'rooms']]
y = data['price']# 訓練模型
X_train, X_test, y_train, y_test = train_test_split(X, y)
model = LinearRegression()
model.fit(X_train, y_train)# 評估
score = model.score(X_test, y_test)
print(f"模型R2分數: {score:.2f}")

調試技巧:

  • 檢查數據分布
  • 嘗試特征工程提高模型性能

1. 電商數據分析系統

2. Web爬蟲應用

需求分析:

  • 使用requests和BeautifulSoup抓取網頁數據
  • 提取特定信息并存儲到CSV文件
  • 實現分頁爬取和異常處理

實現步驟:

import requests
from bs4 import BeautifulSoup
import csvheaders = {'User-Agent': 'Mozilla/5.0'}def scrape_page(url):try:response = requests.get(url, headers=headers)soup = BeautifulSoup(response.text, 'html.parser')# 提取數據示例items = []for item in soup.select('.product-item'):name = item.select_one('.name').text.strip()price = item.select_one('.price').text.strip()items.append({'name': name, 'price': price})return itemsexcept Exception as e:print(f"爬取失敗: {e}")return []# 主程序
base_url = "https://example.com/products?page="
all_items = []for page in range(1, 6):  # 爬取5頁items = scrape_page(base_url + str(page))all_items.extend(items)print(f"已爬取第{page}頁,共{len(items)}條數據")# 保存到CSV
with open('products.csv', 'w', newline='') as f:writer = csv.DictWriter(f, fieldnames=['name', 'price'])writer.writeheader()writer.writerows(all_items)

調試技巧:

  • 使用print輸出中間結果檢查數據提取是否正確
  • 設置time.sleep避免請求過于頻繁
  • 使用try-except捕獲網絡異常

3. 自動化測試框架

需求分析:

  • 支持Web UI自動化測試
  • 生成測試報告
  • 支持并行測試

實現步驟:

from selenium import webdriver
import unittestclass TestWebsite(unittest.TestCase):@classmethoddef setUpClass(cls):cls.driver = webdriver.Chrome()cls.driver.implicitly_wait(10)def test_homepage(self):self.driver.get("http://example.com")self.assertIn("Example Domain", self.driver.title)def test_search(self):self.driver.get("http://example.com")search_box = self.driver.find_element_by_name("q")search_box.send_keys("Python")search_box.submit()self.assertIn("Python", self.driver.page_source)@classmethoddef tearDownClass(cls):cls.driver.quit()if __name__ == "__main__":unittest.main()

調試技巧:

  • 使用driver.save_screenshot()保存錯誤截圖
  • 增加顯式等待避免元素未加載問題
  • 使用HTMLTestRunner生成美觀的測試報告

1. 電商數據分析系統

需求分析:

  • 從CSV文件讀取銷售數據
  • 計算每日/每月銷售額
  • 生成可視化報表

實現步驟:

import pandas as pd
import matplotlib.pyplot as pltdef sales_analysis():# 1. 讀取數據df = pd.read_csv('sales.csv')# 2. 數據處理df['date'] = pd.to_datetime(df['date'])daily_sales = df.groupby(df['date'].dt.date)['amount'].sum()# 3. 可視化plt.figure(figsize=(10,6))daily_sales.plot(kind='bar')plt.title('每日銷售額')plt.savefig('daily_sales.png')

調試技巧:

  • 使用df.head()檢查數據讀取是否正確
  • 打印中間結果驗證數據處理邏輯

2. 天氣查詢應用

需求分析:

  • 調用天氣API獲取實時數據
  • 支持多城市查詢
  • 緩存歷史查詢記錄

實現步驟:

import requests
import jsonclass WeatherApp:def __init__(self, api_key):self.api_key = api_keyself.history = {}def get_weather(self, city):url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={self.api_key}"response = requests.get(url)data = json.loads(response.text)self.history[city] = datareturn data

調試技巧:

  • 檢查API響應狀態碼
  • 使用try-except處理網絡異常

3. 自動化測試框架

需求分析:

  • 支持Web UI自動化測試
  • 生成測試報告
  • 支持并行測試

實現步驟:

from selenium import webdriver
import unittestclass TestWebsite(unittest.TestCase):@classmethoddef setUpClass(cls):cls.driver = webdriver.Chrome()def test_homepage(self):self.driver.get("http://example.com")self.assertIn("Example", self.driver.title)@classmethoddef tearDownClass(cls):cls.driver.quit()

調試技巧:

  • 添加顯式等待處理元素加載
  • 使用Page Object模式提高可維護性

4. 機器學習房價預測

需求分析:

  • 使用線性回歸模型
  • 評估模型性能
  • 部署預測接口

實現步驟:

from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split# 加載數據
data = pd.read_csv('housing.csv')
X = data[['size', 'rooms']]
y = data['price']# 訓練模型
X_train, X_test, y_train, y_test = train_test_split(X, y)
model = LinearRegression()
model.fit(X_train, y_train)# 評估
score = model.score(X_test, y_test)
print(f"模型R2分數: {score:.2f}")

調試技巧:

  • 檢查數據分布
  • 嘗試特征工程提高模型性能

5. 區塊鏈簡易實現

需求分析:

  • 實現區塊鏈數據結構
  • 支持交易驗證
  • 工作量證明機制

實現步驟:

import hashlib
import json
from time import timeclass Block:def __init__(self, index, transactions, timestamp, previous_hash):self.index = indexself.transactions = transactionsself.timestamp = timestampself.previous_hash = previous_hashself.hash = self.calculate_hash()def calculate_hash(self):block_string = json.dumps(self.__dict__, sort_keys=True)return hashlib.sha256(block_string.encode()).hexdigest()

調試技巧:

  • 打印區塊哈希驗證計算邏輯
  • 使用單元測試驗證區塊鏈完整性
  1. 計算器程序
# 簡單計算器實現
import operatordef calculator():operations = {'+': operator.add,'-': operator.sub,'*': operator.mul,'/': operator.truediv}num1 = float(input("輸入第一個數字: "))op = input("選擇操作(+ - * /): ")num2 = float(input("輸入第二個數字: "))result = operations[op](num1, num2)print(f"結果: {result}")calculator()
  1. 文件管理系統
# 基礎文件管理
import osdef file_manager():while True:print("\n文件管理系統")print("1. 列出文件")print("2. 創建文件")print("3. 刪除文件")print("4. 退出")choice = input("選擇操作: ")if choice == '1':files = os.listdir('.')print("當前目錄文件:")for f in files:print(f)elif choice == '2':filename = input("輸入文件名: ")with open(filename, 'w') as f:f.write("")print(f"文件 {filename} 已創建")elif choice == '3':filename = input("輸入要刪除的文件名: ")if os.path.exists(filename):os.remove(filename)print(f"文件 {filename} 已刪除")else:print("文件不存在")elif choice == '4':breakelse:print("無效選擇")file_manager()
  1. 網絡爬蟲
# 簡單網頁爬蟲
import requests
from bs4 import BeautifulSoupdef simple_crawler(url):try:response = requests.get(url)soup = BeautifulSoup(response.text, 'html.parser')print(f"網頁標題: {soup.title.string}")print("所有鏈接:")for link in soup.find_all('a'):print(link.get('href'))except Exception as e:print(f"錯誤: {e}")simple_crawler('https://www.python.org')
  1. Web應用(Flask/Django)
# Flask示例
from flask import Flaskapp = Flask(__name__)@app.route('/')
def hello():return "Hello, Python!"if __name__ == '__main__':app.run()
  1. 數據可視化
# 使用matplotlib繪圖
import matplotlib.pyplot as pltdef plot_example():x = [1, 2, 3, 4, 5]y = [2, 4, 6, 8, 10]plt.plot(x, y)plt.title("簡單折線圖")plt.xlabel("X軸")plt.ylabel("Y軸")plt.show()plot_example()

項目開發建議

  1. 從簡單項目開始:先完成基礎功能,再逐步添加復雜特性
  2. 版本控制:使用Git管理代碼版本
  3. 文檔編寫:為每個項目編寫README說明
  4. 測試驅動:先寫測試用例再開發功能
  5. 代碼重構:定期優化代碼結構和性能

每天學習2-3小時,堅持項目實踐,1個月后你將掌握Python實際開發能力!
建議學習路徑:

  1. 第1周: 基礎語法和函數
  2. 第2周: 面向對象編程
  3. 第3周: 標準庫和項目實踐
  4. 第4周: 高級特性和框架學習

常見問題

  1. Python版本選擇

    • 推薦使用Python 3.8+版本,新特性更豐富且兼容性好
    • 使用python --version檢查當前版本
  2. 虛擬環境使用

    # 創建虛擬環境
    python -m venv myenv# 激活虛擬環境(Linux/Mac)
    source myenv/bin/activate# 安裝包到虛擬環境
    pip install package_name# 退出虛擬環境
    deactivate
    
  3. 性能優化技巧

    • 使用列表推導式替代循環
    # 傳統方式
    squares = []
    for x in range(10):squares.append(x**2)# 列表推導式
    squares = [x**2 for x in range(10)]
    
    • 使用生成器節省內存
    # 生成器表達式
    gen = (x**2 for x in range(1000000))# 生成器函數
    def generate_squares(n):for x in range(n):yield x**2
    
  4. 模塊導入錯誤

    try:import requests
    except ImportError:print("請先安裝requests模塊: pip install requests")
    
  5. 編碼問題

    • 在文件開頭添加# -*- coding: utf-8 -*-解決中文編碼問題
    • 使用.encode('utf-8').decode('utf-8')處理字符串編碼
  6. 性能優化

    • 使用timeit模塊測試代碼執行時間
    • 避免不必要的循環和遞歸

調試技巧

  1. print調試

    print(f"變量值: {variable}")  # 簡單有效
    
  2. 日志記錄進階

    import logging# 配置日志
    logging.basicConfig(level=logging.DEBUG,format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',filename='app.log'
    )# 不同級別日志
    logging.debug('調試信息')
    logging.info('普通信息')
    logging.warning('警告信息')
    logging.error('錯誤信息')
    logging.critical('嚴重錯誤')
    
  3. 性能分析

    import cProfiledef slow_function():total = 0for i in range(1000000):total += ireturn total# 運行性能分析
    cProfile.run('slow_function()')
    
  4. 內存分析

    import tracemalloctracemalloc.start()# 你的代碼
    data = [i for i in range(1000000)]snapshot = tracemalloc.take_snapshot()
    top_stats = snapshot.statistics('lineno')for stat in top_stats[:10]:print(stat)
    
  5. pdb調試器

    import pdb; pdb.set_trace()  # 設置斷點
    
  6. 日志記錄

    import logging
    logging.basicConfig(level=logging.DEBUG)
    logging.debug('調試信息')
    
  7. IDE調試工具

    • 使用VS Code/PyCharm等IDE的調試功能
    • 設置斷點、單步執行、查看變量值
  8. 異常處理

    try:# 可能出錯的代碼
    except Exception as e:print(f"錯誤類型: {type(e).__name__}")print(f"錯誤詳情: {str(e)}")
    

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/bicheng/75638.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/75638.shtml
英文地址,請注明出處:http://en.pswp.cn/bicheng/75638.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

批量刪除git本地分支和遠程分支命令

1、按照關鍵詞開頭匹配刪除遠程分支 git branch -r | grep "origin/feature/develop-1"| sed s/origin\///g | xargs -n 1 git push origin --delete git branch -r 列出所有遠端分支。 grep "origin/feature/develop-1" 模糊匹配分支名稱包含"orig…

上市電子制造企業如何實現合規的質量文件管理?

浙江潔美電子科技股份有限公司成立于2001年&#xff0c;是一家專業為片式電子元器件(被動元件、分立器件、集成電路及LED)配套生產電子薄型載帶、上下膠帶、離型膜、流延膜等產品的國家高新技術企業&#xff0c;主要產品有分切紙帶、打孔經帶、壓孔紙帶、上下膠帶、塑料載帶及其…

leetcode數組-有序數組的平方

題目 題目鏈接&#xff1a;https://leetcode.cn/problems/squares-of-a-sorted-array/ 給你一個按 非遞減順序 排序的整數數組 nums&#xff0c;返回 每個數字的平方 組成的新數組&#xff0c;要求也按 非遞減順序 排序。 輸入&#xff1a;nums [-4,-1,0,3,10] 輸出&#xff…

基于微信小程序的醫院掛號預約系統設計與實現

摘 要 現代經濟快節奏發展以及不斷完善升級的信息化技術&#xff0c;讓傳統數據信息的管理升級為軟件存儲&#xff0c;歸納&#xff0c;集中處理數據信息的管理方式。本微信小程序醫院掛號預約系統就是在這樣的大環境下誕生&#xff0c;其可以幫助管理者在短時間內處理完畢龐大…

密碼學基礎——DES算法

前面的密碼學基礎——密碼學文章中介紹了密碼學相關的概念&#xff0c;其中簡要地對稱密碼體制(也叫單鑰密碼體制、秘密密鑰體制&#xff09;進行了解釋&#xff0c;我們可以知道單鑰體制的加密密鑰和解密密鑰相同&#xff0c;單鑰密碼分為流密碼和分組密碼。 流密碼&#xff0…

Redis分布式鎖詳解

Redis分布式鎖詳解 分布式鎖是在分布式系統中實現互斥訪問共享資源的重要機制。Redis因其高性能和原子性操作特性&#xff0c;常被用來實現分布式鎖。 一、基礎實現方案 1. SETNX EXPIRE方案&#xff08;基本版&#xff09; # 加鎖 SETNX lock_key unique_value # 設置唯…

創建Linux虛擬環境并遠程連接,finalshell自定義壁紙

安裝VMware 這里不多贅述。 掛載Linux系統 1). 打開Vmware虛擬機&#xff0c;打開 編輯 -> 虛擬網絡編輯器(N) 選擇 NAT模式&#xff0c;然后選擇右下角的 更改設置。 設置子網IP為 192.168.100.0&#xff0c;然后選擇 應用 -> 確定。 解壓 CentOS7-1.zip 到一個比較大…

podman和與docker的比較 及podman使用

Podman 與 Docker 的比較和區別 架構差異 Docker&#xff1a;采用客戶端 - 服務器&#xff08;C/S&#xff09;架構&#xff0c;有一個以 root 權限運行的守護進程 dockerd 來管理容器的生命周期。客戶端&#xff08;docker 命令行工具&#xff09;與守護進程進行通信&#x…

【Easylive】HttpServletRequest、HttpServletResponse、HttpSession 介紹

【Easylive】項目常見問題解答&#xff08;自用&持續更新中…&#xff09; 匯總版 這三個是 Java Web 開發&#xff08;Servlet/JSP&#xff09;的核心接口&#xff0c;用于處理 HTTP 請求和響應 以及 用戶會話管理。它們在 Spring MVC&#xff08;Controller&#xff09;中…

Markdown使用說明

以下是Markdown基礎使用教程及分割線展示方法&#xff1a; &#x1f4dd; Markdown基礎使用教程 1. 標題 # 一級標題 ## 二級標題 ### 三級標題2. 文本樣式 *斜體* 或 _斜體_ **加粗** 或 __加粗__ ***加粗斜體*** 或 ___加粗斜體___ ~~刪除線~~3. 列表 - 無序列表項 * 另一…

Jmeter的壓測使用

Jmeter基礎功能回顧 一、創建Jmeter腳本 1、錄制新建 &#xff08;1&#xff09;適用群體&#xff1a;初學者 2、手動創建 &#xff08;1&#xff09;需要了解Jmeter的常用組件 元件&#xff1a;多個類似功能組件的容器&#xff08;類似于類&#xff09; 各元件作用 組件…

【rabbitmq基礎】

RabbitMq基礎 1.概念2.數據隔離3.使用控制臺向mq傳遞消息1.創建兩個隊列-“測試隊列”&#xff0c;“測試隊列2”2.創建一個交換機-"測試交換機"3.測試發送消息3.1讓交換機和隊列進行綁定3.2發送消息3.3查看消息 4.創建虛擬主機5.java使用rabbitmq5.1 發送消息5.2 消…

加固計算機廠家 | 工業加固筆記本電腦廠家

北京魯成偉業科技發展有限公司&#xff08;以下簡稱“魯成偉業”&#xff09;成立于2005年&#xff0c;是集研發、生產、銷售與服務于一體的高新技術企業&#xff0c;專注于加固計算機、工業加固筆記本電腦及特種計算機的研發與制造。憑借20年的技術積累與行業深耕&#xff0c;…

鏈路聚合配置命令

技術信息 加入捆綁組&#xff0c;加大鏈路間帶寬等 配置命令 華三 靜態聚合 將接口加入聚合口后再進行配置 //創建靜態鏈路聚合口1&#xff0c;不啟用lacp[SWB]interface Bridge-Aggregation 1 [SWB-Bridge-Aggregation1]port link-type trunk [SWB-Bridge-Aggregation…

ekf-imu --- 四元數乘法符號 ? 的含義

? 表示四元數的乘法運算&#xff1a; 用于組合兩個四元數代表的旋轉。四元數乘法是非交換的&#xff08;即順序不同結果不同&#xff09;&#xff0c;其定義如下&#xff1a; 若兩個四元數分別為&#xff1a; qq0q1iq2jq3k, pp0p1ip2jp3k, 則它們的乘積為&#xff1a;4*1 …

論文閱讀Diffusion Autoencoders: Toward a Meaningful and Decodable Representation

原文框架圖&#xff1a; 官方代碼&#xff1a; https://github.com/phizaz/diffae/blob/master/interpolate.ipynb 主要想記錄一下模型的推理過程 &#xff1a; %load_ext autoreload %autoreload 2 from templates import * device cuda:1 conf ffhq256_autoenc() # pri…

OpenVLA-OFT——微調VLA的三大關鍵設計:并行解碼、動作分塊、連續動作表示以及L1回歸目標

前言 25年3.26日&#xff0c;這是一個值得紀念的日子&#xff0c;這一天&#xff0c;我司「七月在線」的定位正式升級為了&#xff1a;具身智能的場景落地與定制開發商 &#xff0c;后續則從定制開發 逐步過渡到 標準產品化 比如25年q2起&#xff0c;在定制開發之外&#xff0…

【論文閱讀】Dynamic Adversarial Patch for Evading Object Detection Models

一、介紹 這篇文章主要是針對目標檢測框架的攻擊&#xff0c;不同于現有的攻擊方法&#xff0c;該論文主要的側重點是考慮視角的變化問題&#xff0c;通過在車上布置多個顯示器&#xff0c;利用視角動態選擇哪一個顯示器播放攻擊內容&#xff0c;通過這種方法達到隱蔽與攻擊的…

多模態技術概述(一)

1.1 多模態技術簡介 1.1.1 什么是多模態 多模態(Multimodal)涉及多種不同類型數據或信號的處理和融合&#xff0c;每種數據類型或信號被稱為一種模態。常見的模態包括文本、圖像、音頻、視頻等。多模態技術旨在同時利用這些不同模態的數據&#xff0c;以實現更全面、更準確的理…

nginx2

Nginx反向代理(七層代理)、Nginx的TCP/UDP調度器(四層代理)、 一、Nginx反向代理(七層代理) 步驟&#xff1a; ? 部署后端web服務器集群 ? 配置Nginx代理服務器 ? 配置upstream集群池 ? 調節集群池權重比 <img src"/home/student/Deskt…