1. 前言 Python 是一種廣受初學者與專業人士喜愛的程式語言。其中,「方法(Method)」是學習 Python 程式設計時不可或缺的重要概念之一。 所謂方法,是物件導向程式設計(OOP)的核心要素之一,也是支撐 Python 靈活性與功能性的關鍵機制。透過理解與函式(Function)的差異與實際使用範例,即使是初學者也能提升程式效率與實現程式碼重複利用。 本篇文章將系統性地介紹 Python 方法的基本概念與進階應用。閱讀後你將學到以下內容:什麼是方法?它與函式有何不同? 如何使用實例方法、類別方法與靜態方法 Python 中特殊方法(Magic Method)的活用方式 內建資料型別(如 List、Dictionary 等)提供的便利方法 實務範例中的方法應用 本教學不僅適合 Python 初學者建立基礎知識,也能幫助中高階開發者掌握更進階的使用技巧。那麼,我們就從「什麼是方法」開始深入了解吧!
2. 什麼是 Python 方法?深入解說與函式的差異 Python 中的方法是在物件導向程式設計(OOP)語境下使用的「類似函式的結構」。但與函式不同,方法的特點在於它必須綁定於某個物件實例來運作。為了幫助你理解,我們將透過比較方式來說明它與函式的差異。方法的定義與特性 方法是定義於類別(class)內的函式,用於操作該類別的實例(Instance)。通常會使用參數 self
表示該方法所屬的實例,這使方法能夠存取與操作實例的屬性。 範例:方法的基本結構 class SampleClass:
def example_method(self):
print("This is a method!")
# 建立實例並呼叫方法
obj = SampleClass()
obj.example_method()
輸出結果:This is a method!
上例中的 example_method
就是方法。透過類別實例 obj
呼叫該方法時,self
會指向該實例。與函式的差異 下表整理出方法與函式的主要差異:項目 方法(Method) 函式(Function) 定義位置 定義於類別內部 可於類別外部定義 呼叫方式 需透過實例或類別呼叫 可直接呼叫 關聯對象 綁定於特定物件(透過 self) 與任何物件無關 用途 操作物件內部資料 執行通用處理
範例:函式的基本結構 def example_function():
print("This is a function!")
# 直接呼叫函式
example_function()
方法的用途與優勢 在操作物件資料時,方法提供了高度的靈活性。你可以利用方法初始化、更新或顯示物件的屬性,提升程式的結構與可讀性。 範例:方法的應用優勢 class Counter:
def __init__(self):
self.count = 0
def increment(self):
self.count += 1
def display(self):
print(f"Count: {self.count}")
counter = Counter()
counter.increment()
counter.increment()
counter.display()
輸出結果:Count: 2
如上所示,透過 increment
與 display
方法,我們可以輕鬆操作並顯示 Counter 實例的狀態。方法與函式的選擇指引 函式: 適用於與類別無關的通用邏輯。 例如:數學計算、字串處理(如 len()
、sum()
等)。 方法: 適用於處理與類別或物件狀態相關的邏輯。 例如:變更物件屬性、處理物件資料。 3. 方法的種類與使用方式(實例 / 類別 / 靜態) 在 Python 中,方法可分為三種類型。了解每種方法的用途與使用方式,有助於根據實際需求選擇最合適的實作方式。本節將說明實例方法、類別方法與靜態方法的差異與使用範例。3.1. 實例方法 概要 實例方法是與類別的實例(物件)綁定的普通方法。它的第一個參數是 self
,代表呼叫該方法的具體實例,並可操作該實例的屬性。 範例:實例方法的使用 class Person:
def __init__(self, name):
self.name = name # 設定實例屬性
def greet(self):
print(f"Hello, my name is {self.name}.")
# 建立實例並呼叫方法
person = Person("Alice")
person.greet()
輸出:Hello, my name is Alice.
主要用途 3.2. 類別方法 概要 類別方法是與整個類別綁定的函式。第一個參數是 cls
,代表類別本身,並可操作類別層級的屬性。使用 @classmethod
裝飾器來定義。 範例:類別方法的使用 class Circle:
pi = 3.14 # 類別屬性
@classmethod
def calculate_area(cls, radius):
return cls.pi * radius ** 2
# 透過類別直接呼叫
area = Circle.calculate_area(5)
print(f"Area of the circle: {area}")
輸出:Area of the circle: 78.5
主要用途 範例:替代建構子的定義 class Person:
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def from_string(cls, data_string):
name, age = data_string.split(",")
return cls(name, int(age))
# 透過字串資料建立實例
person = Person.from_string("Bob,30")
print(person.name, person.age)
輸出:Bob 30
3.3. 靜態方法 概要 靜態方法不依賴於任何實例或類別,它不接受 self
或 cls
作為參數。通常用於實作與類別邏輯相關但不需存取內部狀態的功能。定義時需使用 @staticmethod
裝飾器。 範例:靜態方法的使用 class Math:
@staticmethod
def add(x, y):
return x + y
# 直接透過類別呼叫
result = Math.add(3, 5)
print(f"Sum: {result}")
輸出:Sum: 8
主要用途 不需要存取類別或實例屬性的通用處理。 定義工具函式或輔助邏輯。 3.4. 三種方法的比較表 類型 裝飾器 第一參數 主要用途 實例方法 無 self 操作實例的屬性與資料。 類別方法 @classmethod cls 操作類別屬性或定義替代建構子。 靜態方法 @staticmethod 無 執行與類別或實例無關的邏輯。
4. 認識特殊方法(Magic Methods) Python 中的特殊方法(Magic Methods)可用來客製化物件的行為,例如初始化、比較、字串表示等。這些方法的名稱通常以雙底線包圍(例如:__init__
),因此又被稱為「Dunder Methods」。 本節將介紹 Python 中常見的特殊方法,並搭配實用範例說明如何使用。4.1. 特殊方法的基本用途 在定義類別時透過覆寫特殊方法,可以客製化以下操作:物件初始化 (如:__init__
)字串表示 (如:__str__
)比較運算 (如:__eq__
)運算子操作 (如:__add__
) 範例:__init__
方法 class Product:
def __init__(self, name, price):
self.name = name
self.price = price
item = Product("Book", 1500)
print(item.name, item.price)
輸出:Book 1500
4.2. 常見的特殊方法 __init__
:初始化物件__str__
:物件的字串表示用於 print()
或 str()
呼叫時返回可讀字串。 範例 class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def __str__(self):
return f"{self.name} costs {self.price} yen."
item = Product("Book", 1500)
print(item)
輸出:Book costs 1500 yen.
__len__
:定義物件長度class CustomList:
def __init__(self, items):
self.items = items
def __len__(self):
return len(self.items)
my_list = CustomList([1, 2, 3])
print(len(my_list))
輸出:3
__eq__
:自訂等號比較class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __eq__(self, other):
return self.name == other.name and self.age == other.age
person1 = Person("Alice", 30)
person2 = Person("Alice", 30)
print(person1 == person2)
輸出:True
__add__
:自訂加法運算class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
def __str__(self):
return f"Point({self.x}, {self.y})"
point1 = Point(1, 2)
point2 = Point(3, 4)
result = point1 + point2
print(result)
輸出:Point(4, 6)
4.3. 特殊方法的實務應用 範例:自定義類別中使用特殊方法 class BankAccount:
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
def __str__(self):
return f"{self.owner}'s account balance: {self.balance} yen"
def __add__(self, other):
return BankAccount(self.owner, self.balance + other.balance)
account1 = BankAccount("Alice", 5000)
account2 = BankAccount("Alice", 3000)
merged_account = account1 + account2
print(merged_account)
輸出:Alice's account balance: 8000 yen
4.4. 使用特殊方法的好處 提升可讀性 :讓操作物件的方式更直覺。客製化功能 :根據類別需求定義專屬行為。展現 Python 的彈性 :可擴充內建運算子與函式行為。5. 內建資料型別的方法總覽 在 Python 中,像是串列(list)、字典(dict)、字串(str)等常見的內建資料型別,都內建了許多實用的方法。本章節將以這三種最常用的資料型別為主,透過範例介紹它們的常見方法與使用方式。5.1. 串列(list)的方法 串列是 Python 中最常見的資料型別之一,用於處理一系列項目。append()
在串列的末尾新增一個元素。 範例 fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits)
輸出:['apple', 'banana', 'cherry']
extend()
將另一個串列的所有元素加入原串列中。 範例 numbers = [1, 2, 3]
numbers.extend([4, 5, 6])
print(numbers)
輸出:[1, 2, 3, 4, 5, 6]
insert()
在指定的位置插入元素。 範例 colors = ["red", "blue"]
colors.insert(1, "green")
print(colors)
輸出:['red', 'green', 'blue']
remove()
刪除串列中第一次出現的指定值。 範例 numbers = [1, 2, 3, 2]
numbers.remove(2)
print(numbers)
輸出:[1, 3, 2]
sort()
將串列中的元素按升序排序。 範例 numbers = [5, 3, 8, 1]
numbers.sort()
print(numbers)
輸出:[1, 3, 5, 8]
5.2. 字典(dict)的方法 字典是一種鍵(key)與值(value)配對的資料型別,適合儲存結構化資料。get()
取得指定鍵對應的值,如果鍵不存在,則返回預設值。 範例 person = {"name": "Alice", "age": 30}
print(person.get("name"))
print(person.get("gender", "Not specified"))
輸出:Alice
Not specified
keys()
取得所有鍵的列表。 範例 person = {"name": "Alice", "age": 30}
print(person.keys())
輸出:dict_keys(['name', 'age'])
values()
取得所有值的列表。 範例 person = {"name": "Alice", "age": 30}
print(person.values())
輸出:dict_values(['Alice', 30])
items()
取得鍵值對的列表,格式為 tuple。 範例 person = {"name": "Alice", "age": 30}
print(person.items())
輸出:dict_items([('name', 'Alice'), ('age', 30)])
update()
更新字典內容,若鍵已存在則覆蓋,否則新增。 範例 person = {"name": "Alice"}
person.update({"age": 30, "gender": "Female"})
print(person)
輸出:{'name': 'Alice', 'age': 30, 'gender': 'Female'}
5.3. 字串(str)的方法 字串操作是 Python 中最常見的任務之一。upper()
將字串轉換為全大寫。 範例 text = "hello"
print(text.upper())
輸出:HELLO
lower()
將字串轉換為全小寫。 範例 text = "HELLO"
print(text.lower())
輸出:hello
replace()
將字串中指定文字替換為其他文字。 範例 text = "I like Python"
print(text.replace("Python", "programming"))
輸出:I like programming
split()
依照指定的分隔符拆分字串,返回串列。 範例 text = "apple,banana,cherry"
print(text.split(","))
輸出:['apple', 'banana', 'cherry']
strip()
移除字串前後的空白字元。 範例 text = " hello "
print(text.strip())
輸出:hello
5.4. 善用內建資料型別的方法 上述介紹的各種方法在實際開發中非常實用,能夠讓你寫出簡潔且具效率的程式碼。善用這些方法能顯著提升日常開發的工作效率。
6. 活用 Python 方法撰寫高效率程式 靈活地使用 Python 方法能讓你的程式邏輯更清晰,處理複雜任務時也更具效率。本節將以實際情境為基礎,介紹方法在資料分析、API 操作、檔案處理等方面的應用範例。6.1. 資料分析中的應用 在進行資料分析時,串列與字典的操作極為常見。以下是條件篩選的範例: 範例:從資料集中篩選符合條件的資料 data = [
{"name": "Alice", "age": 25, "score": 85},
{"name": "Bob", "age": 30, "score": 90},
{"name": "Charlie", "age": 22, "score": 70}
]
# 篩選分數大於等於 80 的人
filtered_data = [person for person in data if person["score"] >= 80]
print(filtered_data)
輸出:[{'name': 'Alice', 'age': 25, 'score': 85}, {'name': 'Bob', 'age': 30, 'score': 90}]
6.2. 操作 API 回傳資料 處理 API 回傳的 JSON 資料時,常需搭配字串與串列方法進行處理。 範例:整理 API 回傳的使用者資料 response = [
{"id": 1, "name": "Alice", "active": True},
{"id": 2, "name": "Bob", "active": False},
{"id": 3, "name": "Charlie", "active": True}
]
# 取得所有活躍使用者名稱(大寫)
active_users = [user["name"].upper() for user in response if user["active"]]
print(active_users)
輸出:['ALICE', 'CHARLIE']
6.3. 檔案處理中的應用 利用 strip()
與 split()
等方法可以簡潔處理文字檔案內容。 範例:讀取檔案並格式化資料 # 建立檔案並寫入資料
with open("data.txt", "w") as file:
file.write("apple,banana,cherry\norange,grape,melon")
# 讀取檔案並轉為串列
with open("data.txt", "r") as file:
content = file.readlines()
# 處理每行並轉為二維串列
data = [line.strip().split(",") for line in content]
print(data)
輸出:[['apple', 'banana', 'cherry'], ['orange', 'grape', 'melon']]
7. 常見問題(FAQ) 在學習 Python 方法的過程中,許多人會遇到一些共通的疑問。以下整理出常見問題並提供清楚的解答,幫助你更深入理解方法的運用。Q1. 方法與函式有什麼不同? 方法與函式的語法相似,但它們的核心差異如下:項目 方法 函式 定義位置 類別內部 可定義於類別外 呼叫方式 透過實例或類別呼叫 可直接呼叫 關聯對象 與特定物件或類別綁定(使用 self 或 cls) 獨立執行,與物件無關 主要用途 操作物件內部資料 執行通用邏輯
Q2. 特殊方法適用於哪些情境? 特殊方法(又稱魔術方法)在以下幾種情境中特別有用:初始化物件: 使用 __init__
自動設定屬性。class Example:
def __init__(self, name):
self.name = name
自訂字串表示方式: 使用 __str__
控制 print()
或 str()
輸出內容。class Example:
def __str__(self):
return "自訂輸出字串"
自訂運算行為: 使用 __add__
、__mul__
等方法定義加法或乘法的邏輯。class Number:
def __add__(self, other):
return "自訂加法"
Q3. 類別方法與靜態方法的差異是什麼? 項目 類別方法 靜態方法 裝飾器 @classmethod @staticmethod 第一參數 cls(代表類別) 無 可存取範圍 可操作類別層級屬性或方法 不依賴類別或實例狀態
使用情境示例如下:@classmethod
def method_name(cls):
pass
@staticmethod
def method_name():
pass
8. 總結與後續學習方向 8.1. 內容回顧 本篇文章完整介紹了 Python 方法的基礎與應用。方法是理解物件導向程式設計的重要一環,也是撰寫高效率程式的核心工具。以下為本文的重點整理:方法的基本概念 方法是綁定於特定物件的函式,用來操作或查詢物件的狀態。 透過理解方法與函式的差異,有助於適當地選用結構。 三種方法類型 實例方法:操作實例屬性與邏輯。 類別方法:操作類別層級屬性與資料。 靜態方法:獨立邏輯,與類別或實例無關。 特殊方法(魔術方法) 內建資料型別的方法 串列、字典、字串等都具備強大且實用的方法,能簡化日常開發。 實務應用範例 資料分析、API 處理、檔案操作、視覺化等皆可活用方法。 解答常見疑問 進一步釐清初學者常見的概念模糊點,例如:方法與函式的差異、特殊方法的用法等。 8.2. 推薦的學習方向 透過本文,你已掌握 Python 方法的基礎,接下來可進一步探索下列主題:深入物件導向設計(OOP) 學習繼承(Inheritance)、多型(Polymorphism)、抽象類別(Abstract Class)等設計原則。 推薦主題:類別繼承、設計模式(Design Patterns)。 裝飾器(Decorator)與進階應用 在掌握 @classmethod
與 @staticmethod
的基礎上,學習自訂裝飾器可大幅提升程式彈性。 推薦主題:@property
、函式包裝。 善用標準與外部函式庫 活用 Python 標準函式庫與第三方套件能加速開發流程。 推薦主題:pandas、NumPy、matplotlib 等。 進行實際專案練習 透過實作專案,累積開發經驗。可從小型專案逐步擴展。 推薦專案:CRUD 系統、資料處理自動化腳本。 活用官方文件 Python documentation
The official Python documentation.…
8.3. 結語 掌握 Python 方法不僅能提升程式品質,還能讓你更有效率地解決問題。未來透過專案實作與持續學習,你將能靈活運用方法,打造出穩定且具可讀性的 Python 應用程式。