掌握 Python 類定義的五大要點
在 Python 中,類是面向對象編程的核心。通過類,我們可以創建自定義數據類型,封裝數據和方法,實現代碼的復用性和模塊化。本文將詳細介紹 Python 類定義的五大要點,幫助你更好地理解和使用類。
1. 定義類的基本語法
首先,讓我們來看看如何定義一個基本的類。類的定義使用 class 關鍵字,后跟類名和冒號。類體包含類的方法和屬性。
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}"
代碼解釋:
- class Dog: 定義了一個名為 Dog 的類。
- species = "Canis familiaris" 是一個類屬性,所有實例共享這個屬性。
- __init__ 方法是一個特殊方法,用于初始化新創建的對象。self 參數代表實例本身。
- description 和 speak 是實例方法,可以通過實例調用。
2. 初始化方法 __init__
__init__ 方法是一個特殊方法,也稱為構造函數。它在創建類的實例時自動調用,用于初始化對象的狀態。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# 創建實例
person1 = Person("Alice", 30)
person2 = Person("Bob", 25)
print(person1.name) # 輸出: Alice
print(person2.age) # 輸出: 25
代碼解釋:
- __init__ 方法接收兩個參數 name 和 age,并將它們賦值給實例的屬性。
- 創建 Person 類的實例時,傳入 name 和 age 參數,這些參數被傳遞給 __init__ 方法。
3. 類屬性 vs 實例屬性
類屬性是所有實例共享的屬性,而實例屬性是每個實例獨有的屬性。
class Car:
# 類屬性
wheels = 4
def __init__(self, make, model):
# 實例屬性
self.make = make
self.model = model
# 創建實例
car1 = Car("Toyota", "Corolla")
car2 = Car("Honda", "Civic")
print(car1.wheels) # 輸出: 4
print(car2.wheels) # 輸出: 4
print(car1.make) # 輸出: Toyota
print(car2.make) # 輸出: Honda
代碼解釋:
- wheels 是一個類屬性,所有 Car 實例共享這個屬性。
- make 和 model 是實例屬性,每個 Car 實例都有自己的 make 和 model 屬性。
4. 方法的類型
Python 類中有三種方法:實例方法、類方法和靜態方法。
- 實例方法:最常用的方法,第一個參數必須是 self,代表實例本身。
- 類方法:使用 @classmethod 裝飾器定義,第一個參數是 cls,代表類本身。
- 靜態方法:使用 @staticmethod 裝飾器定義,不接收 self 或 cls 參數。
class Circle:
pi = 3.14159
def __init__(self, radius):
self.radius = radius
# 實例方法
def area(self):
return Circle.pi * (self.radius ** 2)
# 類方法
@classmethod
def from_diameter(cls, diameter):
return cls(diameter / 2)
# 靜態方法
@staticmethod
def is_positive(number):
return number > 0
# 創建實例
circle1 = Circle(5)
circle2 = Circle.from_diameter(10)
print(circle1.area()) # 輸出: 78.53975
print(circle2.area()) # 輸出: 78.53975
print(Circle.is_positive(5)) # 輸出: True
代碼解釋:
- area 是一個實例方法,計算圓的面積。
- from_diameter 是一個類方法,根據直徑創建 Circle 實例。
- is_positive 是一個靜態方法,判斷一個數是否為正數。
5. 繼承和多態
繼承允許一個類(子類)繼承另一個類(父類)的屬性和方法。多態是指子類可以覆蓋或擴展父類的方法。
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("Subclass must implement this abstract method")
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
class Cat(Animal):
def speak(self):
return f"{self.name} says Meow!"
# 創建實例
dog = Dog("Buddy")
cat = Cat("Whiskers")
print(dog.speak()) # 輸出: Buddy says Woof!
print(cat.speak()) # 輸出: Whiskers says Meow!
代碼解釋:
- Animal 類是一個基類,定義了 speak 方法,但沒有具體實現。
- Dog 和 Cat 類繼承自 Animal 類,并實現了 speak 方法。
- 創建 Dog 和 Cat 實例時,調用各自的 speak 方法。
實戰案例:銀行賬戶管理系統
假設我們要創建一個簡單的銀行賬戶管理系統,包括賬戶類和交易類。我們將使用類和繼承來實現這一功能。
class Account:
def __init__(self, account_number, balance=0):
self.account_number = account_number
self.balance = balance
def deposit(self, amount):
if amount > 0:
self.balance += amount
print(f"Deposited {amount}. New balance: {self.balance}")
else:
print("Deposit amount must be positive.")
def withdraw(self, amount):
if 0 < amount <= self.balance:
self.balance -= amount
print(f"Withdrew {amount}. New balance: {self.balance}")
else:
print("Invalid withdrawal amount.")
def get_balance(self):
return self.balance
class SavingsAccount(Account):
def __init__(self, account_number, balance=0, interest_rate=0.01):
super().__init__(account_number, balance)
self.interest_rate = interest_rate
def add_interest(self):
interest = self.balance * self.interest_rate
self.deposit(interest)
print(f"Added interest of {interest}. New balance: {self.balance}")
# 創建實例
account1 = Account("1234567890", 1000)
savings_account1 = SavingsAccount("0987654321", 2000, 0.02)
account1.deposit(500) # 輸出: Deposited 500. New balance: 1500
account1.withdraw(200) # 輸出: Withdrew 200. New balance: 1300
savings_account1.deposit(1000) # 輸出: Deposited 1000. New balance: 3000
savings_account1.add_interest() # 輸出: Added interest of 60.0. New balance: 3060
代碼解釋:
- Account 類是基類,定義了存款、取款和獲取余額的方法。
- SavingsAccount 類繼承自 Account 類,增加了計算利息的功能。
- 創建 Account 和 SavingsAccount 實例,測試各種方法的調用。
總結
本文介紹了 Python 類定義的五大要點:
- 基本語法:使用 class 關鍵字定義類。
- 初始化方法 init:用于初始化對象的狀態。
- 類屬性 vs 實例屬性:類屬性共享,實例屬性獨有。
- 方法的類型:實例方法、類方法和靜態方法。
- 繼承和多態:子類可以繼承父類的屬性和方法,并可以覆蓋或擴展這些方法。
通過實戰案例,我們進一步鞏固了對類的理解和應用。