💻函式與模組、物件導向程式設計 (OOP) 以及 檔案與資料庫操作 的應用~邱允文

 💻詳細解說 函式與模組物件導向程式設計 (OOP) 以及 檔案與資料庫操作 的應用。


⚙️ F. 函式與模組的應用 (Functions and Modules)

函式 (Function) 和模組 (Module) 是組織程式碼、實現重用和提高可讀性的基本工具。

📌 詳細解說與步驟

  • 函式定義: 函式是一段執行特定任務的程式碼塊,使用 def 關鍵字定義。

  • 模組定義: 模組是一個包含 Python 定義和語句的文件(.py 檔案),用於將相關的程式碼組織在一起。

  • 使用時機:

    • 函式: 任何需要重複執行的邏輯,例如計算、數據驗證或格式化。

    • 模組: 當程式碼量增大,需要邏輯分區,或需要使用外部庫 (例如 math, random) 時。

  • 步驟:

    1. 定義函式: 使用 def function_name(parameters): 結構。

    2. 呼叫函式: 使用 function_name(arguments) 執行。

    3. 使用模組: 使用 import module_namefrom module_name import item 導入。

📝 案例與細節講解 (3個案例)

案例一:使用函式處理數據清洗 (Data Cleaning with Function)

  • 目的: 建立一個可重用的函式,用於統一處理和格式化字串輸入。

  • 函式: normalize_input

  • 細節講解:

    • 函式接收一個字串參數 text,執行去除首尾空白 (.strip()) 和轉換為小寫 (.lower()) 的操作。

    • return 關鍵字將處理後的結果返回給呼叫者。

    • 這確保了無論何時呼叫此函式,數據處理的邏輯都保持一致。

    • Prompt 範例:

      Python
      # 題示詞: 定義一個函式,將輸入的字串去除空白並轉為小寫,然後應用於兩個不同的輸入。
      def normalize_input(text):
          """去除字串首尾空白並轉換為小寫。"""
          processed_text = text.strip().lower()
          return processed_text
      
      input_a = "  PYTHON PROGRAMMING "
      input_b = " Machine Learning "
      
      normalized_a = normalize_input(input_a)
      normalized_b = normalize_input(input_b)
      
      print(f"輸入 A 處理結果: {normalized_a}")
      print(f"輸入 B 處理結果: {normalized_b}")
      

案例二:使用標準模組進行數學計算 (Math Module)

  • 目的: 導入 Python 內建的 math 模組,使用其提供的常數和函式進行計算。

  • 模組/函式: math.pi, math.pow()

  • 細節講解:

    • import math 語句將整個模組導入,你需要使用 math. 前綴來存取其中的項目。

    • math.pi 是一個精確的浮點數常數。

    • math.pow(x, y) 用於計算 xy 次方。

    • 這樣做避免了自己重新實現複雜的數學邏輯。

    • Prompt 範例:

      Python
      # 題示詞: 導入 math 模組,計算半徑為 5 的圓的面積 (A = π * r^2)。
      import math
      
      radius = 5
      # 使用 math.pi 和 math.pow
      area = math.pi * math.pow(radius, 2)
      
      print(f"圓周率 (π): {math.pi}")
      print(f"圓的面積: {area}")
      

案例三:從自定義模組導入功能 (Custom Module Import)

  • 目的: 將業務邏輯放在單獨的檔案 (utils.py) 中,並在主程式中導入使用。

  • 步驟/檔案: utils.py (模組檔) 和 main.py (主程式檔)

  • 細節講解:

    • 假設你創建了一個名為 utils.py 的檔案,裡面定義了 format_currency(amount) 函式。

    • main.py 中使用 from utils import format_currency 語句,可以直接使用函式名而無需 utils. 前綴。

    • 這是一種更乾淨的導入方式,常用於大型專案。

    • Prompt 範例 (假設您已創建 utils.py 檔案):

      Python
      # 題示詞: 假設 utils.py 中定義了 format_currency 函式,請導入並使用它。
      # --- 這是 utils.py 的內容 ---
      # def format_currency(amount):
      #     return f"NT${amount:,.2f}"
      # -----------------------------
      
      # main.py 的程式碼
      from utils import format_currency 
      
      price = 12345.678
      formatted_price = format_currency(price)
      
      print(f"格式化後的價格: {formatted_price}")
      

💎 G. 類別與物件導向程式設計 (OOP)

物件導向程式設計 (Object-Oriented Programming, OOP) 是一種將數據和處理數據的函式(方法)封裝在一起的編程範式。

📌 詳細解說與步驟

  • 類別 (Class): 是一個藍圖或模板,用於創建物件。使用 class 關鍵字定義。

  • 物件 (Object): 是類別的實例,具有屬性(數據)和方法(行為)。

  • 核心概念:

    • 封裝 (Encapsulation): 將數據(屬性)和操作數據的代碼(方法)綁定在一個單元(類別)中。

    • 繼承 (Inheritance): 允許一個類別繼承另一個類別的屬性和方法。

    • 多型 (Polymorphism): 允許不同的類別以自己的方式響應相同的消息(方法呼叫)。

  • 步驟:

    1. 定義類別: 使用 class ClassName:

    2. 定義構造函式: 使用 def __init__(self, ...): 來初始化物件的屬性。

    3. 定義方法: 使用 def method_name(self, ...): 來定義物件的行為。

    4. 實例化物件: 使用 object_name = ClassName(arguments) 創建物件。

📝 案例與細節講解 (3個案例)

案例一:基本類別與物件的創建 (User Class)

  • 目的: 創建一個 User 類別,用於封裝用戶的相關數據和行為。

  • 類別/方法: User, __init__, greet

  • 細節講解:

    • __init__(self, ...) 是特殊方法(構造函式),在創建物件時自動呼叫,用於設定初始屬性。

    • self 參數是必須的,它指向物件自身,用於存取物件的屬性和方法。

    • greet 方法是物件的行為,用於輸出用戶特定的訊息。

    • Prompt 範例:

      Python
      # 題示詞: 定義一個 User 類別,包含 name 和 email 屬性,以及一個 greet 方法。
      class User:
          """表示一個用戶的類別"""
          def __init__(self, name, email):
              self.name = name  # 實例屬性
              self.email = email
      
          def greet(self):
              """用戶打招呼的方法"""
              return f"您好,我是 {self.name}。我的信箱是 {self.email}。"
      
      # 實例化兩個 User 物件
      user1 = User("Alice", "alice@example.com")
      user2 = User("Bob", "bob@example.com")
      
      print(user1.greet())
      print(f"Bob 的 email: {user2.email}")
      

案例二:類別屬性和方法 (Class Attributes and Methods)

  • 目的: 示範如何使用類別屬性來儲存所有物件共享的數據,並使用類別方法進行操作。

  • 屬性/方法: user_count (類別屬性), get_user_count (類別方法)

  • 細節講解:

    • user_count 屬於類別本身,而不是單個物件,因此所有 User 實例共享它。

    • __init__ 中,通過 User.user_count += 1 來追蹤實例的數量。

    • @classmethod 裝飾器將方法標記為類別方法,它接收類別本身 (cls) 作為第一個參數。

    • Prompt 範例:

      Python
      # 題示詞: 在 User 類別中加入 user_count 屬性來追蹤總用戶數,並新增一個類別方法來獲取它。
      class User:
          user_count = 0  # 類別屬性,所有實例共享
      
          def __init__(self, name):
              self.name = name
              User.user_count += 1 # 每次創建實例,計數器 +1
      
          @classmethod
          def get_user_count(cls):
              """返回當前已創建的用戶總數"""
              return cls.user_count
      
      user_a = User("David")
      user_b = User("Eve")
      
      # 透過類別或實例呼叫類別方法
      print(f"目前系統中的總用戶數: {User.get_user_count()}") 
      

案例三:繼承的應用 (Inheritance)

  • 目的: 創建一個子類別 AdminUser 繼承自父類別 User,並添加或覆寫特定功能。

  • 類別: User (父類), AdminUser (子類)

  • 細節講解:

    • class AdminUser(User): 表示 AdminUser 繼承 User 的所有屬性和方法。

    • AdminUser__init__ 中,使用 super().__init__(name, email) 呼叫父類別的構造函式,重用父類的初始化邏輯。

    • 子類可以定義自己獨有的屬性 (privileges) 和方法。

    • Prompt 範例:

      Python
      # 題示詞: 定義 AdminUser 類別繼承 User,並賦予額外的 privileges 屬性。
      class User: # 父類
          def __init__(self, name, email):
              self.name = name
              self.email = email
      
      class AdminUser(User): # 子類繼承父類
          def __init__(self, name, email, privileges):
              # 呼叫父類的構造函式,初始化 name 和 email
              super().__init__(name, email) 
              self.privileges = privileges # 子類特有的屬性
      
          def manage_system(self):
              return f"{self.name} 正在使用權限 {self.privileges} 管理系統。"
      
      admin1 = AdminUser("Manager", "manager@corp.com", ["edit_all", "delete_users"])
      
      print(admin1.manage_system())
      print(f"管理員的信箱: {admin1.email}") # 繼承自 User 類別
      

💾 H. 檔案與資料庫操作 (File and Database Operations)

實際應用程式需要與外部資源互動,最常見的就是檔案系統和資料庫。

📌 詳細解說與步驟

  • 檔案操作: 讀取、寫入或修改儲存在硬碟上的文件(如 .txt, .csv, .json)。

  • 資料庫操作: 通常指使用 SQL 語法與關聯式資料庫(如 SQLite、MySQL)進行數據交換(增、刪、改、查)。

  • 核心工具:

    • 檔案: 內建的 open() 函式配合 with 語句。

    • 資料庫: Python 內建的 sqlite3 模組(用於 SQLite 資料庫)。

📝 案例與細節講解 (3個案例)

案例一:安全地讀取文本檔案 (Reading a Text File Safely)

  • 目的: 讀取一個文本檔案的內容。

  • 函式/語法: open(), with open(...), .read()

  • 細節講解:

    • 使用 with open(filename, mode) as file_object: 是處理檔案的標準且推薦的做法。

    • with 語句會自動處理檔案關閉,即使發生錯誤也不會洩漏資源。

    • 模式 'r' 表示只讀 (Read)。

    • file.read() 一次性讀取整個檔案內容為一個字串。

    • Prompt 範例 (假設存在 data.txt 檔案):

      Python
      # 題示詞: 安全地打開並讀取名為 'data.txt' 的所有內容。
      # 假設 data.txt 內容為: Hello Python\nWelcome to File Handling
      file_name = "data.txt" 
      
      try:
          with open(file_name, 'r', encoding='utf-8') as file:
              content = file.read()
              print("--- 檔案內容 ---")
              print(content)
      except FileNotFoundError:
          print(f"錯誤:指定的檔案 {file_name} 不存在。")
      

案例二:寫入新數據到檔案 (Writing to a Text File)

  • 目的: 將新生成的數據寫入一個文本檔案。

  • 函式/語法: open(), with open(...), .write()

  • 細節講解:

    • 模式 'w' 表示寫入 (Write)。如果檔案已存在,內容將被清空;如果檔案不存在,則會創建新檔案。

    • 模式 'a' 表示追加 (Append),它會在檔案末尾添加新內容而不清空舊內容。

    • .write() 函式只接受字串作為參數。

    • Prompt 範例:

      Python
      # 題示詞: 創建一個名為 'log.txt' 的檔案,並將一條日誌訊息寫入其中。
      log_file = "log.txt"
      log_message = "系統啟動於 2025-11-08 14:00:00\n"
      
      # 使用 'w' 模式創建並寫入
      with open(log_file, 'w', encoding='utf-8') as file:
          file.write(log_message)
      
      # 使用 'a' 模式追加另一條訊息
      with open(log_file, 'a', encoding='utf-8') as file:
          file.write("INFO: 初始化完成。\n")
      
      print(f"日誌訊息已寫入到 {log_file}。")
      

案例三:使用 SQLite 執行資料庫操作 (SQLite Database Operations)

  • 目的: 建立一個 SQLite 資料庫連線,創建一個表格並插入數據。

  • 模組/方法: sqlite3, connect, cursor, execute, commit

  • 細節講解:

    • import sqlite3 是使用內建 SQLite 模組的第一步。

    • sqlite3.connect('my_db.db') 建立連線,如果檔案不存在會自動創建。

    • conn.cursor() 創建游標物件,用於執行 SQL 語句。

    • c.execute() 執行 SQL 語句(如 CREATE TABLE, INSERT INTO)。

    • conn.commit() 必須呼叫,才能將操作永久保存到資料庫檔案。

    • Prompt 範例:

      Python
      # 題示詞: 創建一個名為 'inventory.db' 的資料庫,建立一個 Products 表格並插入一條記錄。
      import sqlite3
      
      db_file = "inventory.db"
      
      try:
          conn = sqlite3.connect(db_file)
          c = conn.cursor()
      
          # 1. 創建表格
          c.execute('''
              CREATE TABLE IF NOT EXISTS Products (
                  id INTEGER PRIMARY KEY,
                  name TEXT,
                  price REAL
              )
          ''')
      
          # 2. 插入數據
          product_data = ('Laptop', 1200.50)
          c.execute("INSERT INTO Products (name, price) VALUES (?, ?)", product_data)
      
          # 3. 提交變更並關閉連線
          conn.commit()
          print(f"資料庫 {db_file} 創建成功,並插入了一條產品記錄。")
      
      except sqlite3.Error as e:
          print(f"資料庫操作錯誤: {e}")
      finally:
          if conn:
              conn.close()
      

留言

這個網誌中的熱門文章

🌻AI 時代自媒體行銷與 SEO 實務操作技巧 ~邱允文

🚀 🚀用AI打造你的自媒體金礦!實戰課程~邱允文

🎁生日, 結婚, 榮升, 榮退, 禮物, 藝術瓶雕🎁天藏地酒🎉