# Python 中的 decorator、`@dataclass` 與 `@abstractmethod` 介紹 在大學的 Python 課程中,我幾乎沒學過 decorator,直到後來才發現這些語法糖在工程實務中非常常見。而像 `@dataclass` 甚至可以幫我們省下不少樣板程式碼。這篇文章就快速介紹三個常見的 Python 裝飾器用法:`@decorator`、`@dataclass`、以及 `@abstractmethod`。 --- ## 1️⃣ decorator: 改變函式行為的小魔法 **Decorator** 是 Python 的 Syntactic sugar,常用來包裝函式或方法,加上額外的功能,例如記錄 log、權限檢查、計時等等。 > 語法糖是由英國電腦科學家彼得·蘭丁發明的一個術語,意指這種語法對語言的功能沒有影響,但是更方便程式設計師使用。 ### 🔹 簡單範例 ```python def my_decorator(func): def wrapper(*args, **kwargs): print("執行前") result = func(*args, **kwargs) print("執行後") return result return wrapper @my_decorator def say_hello(): print("Hello!") say_hello() ``` ### 🧠 等價於: ```python say_hello = my_decorator(say_hello) ``` --- ## 2️⃣ @dataclass: 自動生成 __init__ 等方法 在撰寫資料類別時,常常要寫一堆 __init__、__repr__、__eq__ 等方法,超級無聊又重複。@dataclass 可以幫你自動生成這些樣板代碼! ### 🔹 範例: ```python from dataclasses import dataclass @dataclass class Person: name: str age: int p = Person(name="Alice", age=30) print(p) # 自動有漂亮的 __repr__ ``` ### 🧠 @dataclass 會自動生成: * `__init__` * `__repr__` * `__eq__` * `__hash__`(視情況而定) 如果你要自己定義 __post_init__(類似 constructor 後處理),也可以自訂。 --- ## 3️⃣ @abstractmethod: 強迫子類實作的方法 這是 Python 提供的抽象類別機制,使用 abc 模組,讓你建立「不能被直接實例化」的抽象類,並規定子類一定要實作某些方法。 ### 🔹 使用方式 ```python from abc import ABC, abstractmethod class Animal(ABC): @abstractmethod def speak(self): pass class Dog(Animal): def speak(self): print("Woof") # cat = Animal() # ❌ 會錯,不能直接實例化 dog = Dog() # ✅ 正確,因為實作了 speak() dog.speak() ``` ### ✅ 使用情境 * 設計框架時,先定義接口規範 * 確保所有子類都實作必要功能 * 搭配 `@classmethod` 也能定義抽象 class method --- ### 結語 `@decorator`、`@dataclass` 和` @abstractmethod` 是 Python 中很有用的進階語法,雖然在初學階段不常用到,但在實際工程開發中非常實用,能讓程式更簡潔、彈性、也更容易維護。這些特性也很適合用在設計 pattern、API 架構或資料處理上。
×
Sign in
Email
Password
Forgot password
or
Sign in via Google
Sign in via Facebook
Sign in via X(Twitter)
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
Continue with a different method
New to HackMD?
Sign up
By signing in, you agree to our
terms of service
.