掌握 Python 類定義的五大要點(diǎn)
在 Python 中,類是面向?qū)ο缶幊痰暮诵?。通過類,我們可以創(chuàng)建自定義數(shù)據(jù)類型,封裝數(shù)據(jù)和方法,實(shí)現(xiàn)代碼的復(fù)用性和模塊化。本文將詳細(xì)介紹 Python 類定義的五大要點(diǎn),幫助你更好地理解和使用類。
1. 定義類的基本語法
首先,讓我們來看看如何定義一個(gè)基本的類。類的定義使用 class 關(guān)鍵字,后跟類名和冒號(hào)。類體包含類的方法和屬性。
class Dog:
# 類屬性
species = "Canis familiaris"
# 初始化方法
def __init__(self, name, age):
self.name = name
self.age = age
# 實(shí)例方法
def description(self):
return f"{self.name} is {self.age} years old."
# 另一個(gè)實(shí)例方法
def speak(self, sound):
return f"{self.name} says {sound}"
代碼解釋:
- class Dog: 定義了一個(gè)名為 Dog 的類。
- species = "Canis familiaris" 是一個(gè)類屬性,所有實(shí)例共享這個(gè)屬性。
- __init__ 方法是一個(gè)特殊方法,用于初始化新創(chuàng)建的對(duì)象。self 參數(shù)代表實(shí)例本身。
- description 和 speak 是實(shí)例方法,可以通過實(shí)例調(diào)用。
2. 初始化方法 __init__
__init__ 方法是一個(gè)特殊方法,也稱為構(gòu)造函數(shù)。它在創(chuàng)建類的實(shí)例時(shí)自動(dòng)調(diào)用,用于初始化對(duì)象的狀態(tài)。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# 創(chuàng)建實(shí)例
person1 = Person("Alice", 30)
person2 = Person("Bob", 25)
print(person1.name) # 輸出: Alice
print(person2.age) # 輸出: 25
代碼解釋:
- __init__ 方法接收兩個(gè)參數(shù) name 和 age,并將它們賦值給實(shí)例的屬性。
- 創(chuàng)建 Person 類的實(shí)例時(shí),傳入 name 和 age 參數(shù),這些參數(shù)被傳遞給 __init__ 方法。
3. 類屬性 vs 實(shí)例屬性
類屬性是所有實(shí)例共享的屬性,而實(shí)例屬性是每個(gè)實(shí)例獨(dú)有的屬性。
class Car:
# 類屬性
wheels = 4
def __init__(self, make, model):
# 實(shí)例屬性
self.make = make
self.model = model
# 創(chuàng)建實(shí)例
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 是一個(gè)類屬性,所有 Car 實(shí)例共享這個(gè)屬性。
- make 和 model 是實(shí)例屬性,每個(gè) Car 實(shí)例都有自己的 make 和 model 屬性。
4. 方法的類型
Python 類中有三種方法:實(shí)例方法、類方法和靜態(tài)方法。
- 實(shí)例方法:最常用的方法,第一個(gè)參數(shù)必須是 self,代表實(shí)例本身。
- 類方法:使用 @classmethod 裝飾器定義,第一個(gè)參數(shù)是 cls,代表類本身。
- 靜態(tài)方法:使用 @staticmethod 裝飾器定義,不接收 self 或 cls 參數(shù)。
class Circle:
pi = 3.14159
def __init__(self, radius):
self.radius = radius
# 實(shí)例方法
def area(self):
return Circle.pi * (self.radius ** 2)
# 類方法
@classmethod
def from_diameter(cls, diameter):
return cls(diameter / 2)
# 靜態(tài)方法
@staticmethod
def is_positive(number):
return number > 0
# 創(chuàng)建實(shí)例
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 是一個(gè)實(shí)例方法,計(jì)算圓的面積。
- from_diameter 是一個(gè)類方法,根據(jù)直徑創(chuàng)建 Circle 實(shí)例。
- is_positive 是一個(gè)靜態(tài)方法,判斷一個(gè)數(shù)是否為正數(shù)。
5. 繼承和多態(tài)
繼承允許一個(gè)類(子類)繼承另一個(gè)類(父類)的屬性和方法。多態(tài)是指子類可以覆蓋或擴(kuò)展父類的方法。
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!"
# 創(chuàng)建實(shí)例
dog = Dog("Buddy")
cat = Cat("Whiskers")
print(dog.speak()) # 輸出: Buddy says Woof!
print(cat.speak()) # 輸出: Whiskers says Meow!
代碼解釋:
- Animal 類是一個(gè)基類,定義了 speak 方法,但沒有具體實(shí)現(xiàn)。
- Dog 和 Cat 類繼承自 Animal 類,并實(shí)現(xiàn)了 speak 方法。
- 創(chuàng)建 Dog 和 Cat 實(shí)例時(shí),調(diào)用各自的 speak 方法。
實(shí)戰(zhàn)案例:銀行賬戶管理系統(tǒng)
假設(shè)我們要?jiǎng)?chuàng)建一個(gè)簡單的銀行賬戶管理系統(tǒng),包括賬戶類和交易類。我們將使用類和繼承來實(shí)現(xiàn)這一功能。
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}")
# 創(chuàng)建實(shí)例
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 類,增加了計(jì)算利息的功能。
- 創(chuàng)建 Account 和 SavingsAccount 實(shí)例,測(cè)試各種方法的調(diào)用。
總結(jié)
本文介紹了 Python 類定義的五大要點(diǎn):
- 基本語法:使用 class 關(guān)鍵字定義類。
- 初始化方法 init:用于初始化對(duì)象的狀態(tài)。
- 類屬性 vs 實(shí)例屬性:類屬性共享,實(shí)例屬性獨(dú)有。
- 方法的類型:實(shí)例方法、類方法和靜態(tài)方法。
- 繼承和多態(tài):子類可以繼承父類的屬性和方法,并可以覆蓋或擴(kuò)展這些方法。
通過實(shí)戰(zhàn)案例,我們進(jìn)一步鞏固了對(duì)類的理解和應(yīng)用。