昨天我們學了繼承、覆寫、多型,今天要深入探討 OOP 的另一個核心封裝。
封裝的目的,是讓物件的內部實作與外部使用分開,避免程式亂掉,也保障資料安全。
就像你用手機,你只需要點拍照按鈕,不用知道鏡頭內部怎麼運作。
這就是封裝的概念。
Python的存取控制
Python沒有像Java、C++那樣的嚴格關鍵字(public、private)
但透過命名規則來模擬存取控制:
public(公開):所有人都能存取(預設情況)。
protected(受保護):建議只在類別和子類別中使用。
private(私有):外部不能直接存取。
公開屬性
class Student:
def init(self, name, score):
self.name = name # 公開屬性
self.score = score
student = Student("Allen", 90)
print(student.name) # 可以直接存取
print(student.score)
受保護屬性(Protected,單底線 _)
class Student:
def init(self, name, score):
self._score = score # 建議僅限內部或子類別使用
def show_score(self):
print(f"分數:{self._score}")
student = Student("Allen", 95)
print(student._score) # 雖然可以存取,但不建議
student.show_score()
單底線 _ 是一種約定俗成的規範,提醒這不是給你直接用的。
私有屬性(Private,雙底線 __)
class BankAccount:
def init(self, owner, balance):
self.owner = owner
self.__balance = balance # 私有屬性
def deposit(self, amount):
self.__balance += amount
def show_balance(self):
print(f"{self.owner} 的餘額:{self.__balance}")
account = BankAccount("Mary", 1000)
account.deposit(500)
account.show_balance()
print(account.balance) # 會報錯,無法直接存取。
balance 無法直接存取,確保資料不會被隨意修改。
class BankAccount:
def init(self, owner, balance):
self.__balance = balance
self.owner = owner
def get_balance(self): # Getter
return self.__balance
def set_balance(self, amount): # Setter
if amount >= 0:
self.__balance = amount
else:
print("餘額不能是負數!")
account = BankAccount("Allen", 500)
print(account.get_balance()) # 500
account.set_balance(1000)
print(account.get_balance()) # 1000
account.set_balance(-50) # 餘額不能是負數!
這樣能控制資料修改的規則,避免出現不合理的值。
真實案例:ATM 系統
class ATM:
def init(self, pin, balance=0):
self.__pin = pin
self.__balance = balance
def check_pin(self, pin):
return self.__pin == pin
def withdraw(self, pin, amount):
if self.check_pin(pin):
if amount <= self.__balance:
self.__balance -= amount
print(f"成功提領 {amount} 元,餘額 {self.__balance} 元。")
else:
print("餘額不足!")
else:
print("密碼錯誤!")
atm = ATM("1234", 1000)
atm.withdraw("1234", 500) # 成功
atm.withdraw("0000", 300) # 密碼錯誤!
學會了封裝與存取控制,理解了如何保護程式中的資料與邏輯。
明天,我們將正式走向進階Python學習錯誤處理與自訂例外(Custom Exceptions),讓程式更穩健。