Python面向对象编程:用对象思维构建数字世界
一、从现实世界到代码世界:理解对象思维
想象你要开发一个虚拟动物园:
- 传统方式:编写函数
feed_animal()
、clean_cage()
、record_health()
- 面向对象方式:创建
Animal
类,每个动物都是独立对象,具备属性和行为
面向对象编程(OOP)的核心是用现实世界的思维方式构建软件系统。在Python中,万物皆对象,这种编程范式让我们能够:
- 将复杂系统分解为独立模块
- 通过封装隐藏实现细节
- 通过继承实现代码复用
- 通过多态实现灵活扩展
1.1 类与对象的本质关系
class Smartphone:
def __init__(self, brand, os):
self.brand = brand # 实例属性
self.os = os
self.__battery = 100 # 私有属性
def charge(self): # 方法
self.__battery = 100
@property
def battery_level(self): # 属性装饰器
return f"{
self.__battery}%"
# 创建对象实例
iphone = Smartphone("Apple", "iOS")
android = Smartphone("Samsung", "Android")
print(iphone.battery_level) # 100%
android.charge()
类(Class)是蓝图模板,对象(Object)是具体实例。就像建筑设计图(类)和实际建筑物(对象)的关系。
二、面向对象四大支柱详解
2.1 封装(Encapsulation)
实践案例:银行账户系统
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.__balance = balance # 私有属性
def deposit(self, amount):
if amount > 0:
self.__balance += amount
self.__log_transaction(f"Deposit: +{
amount}")
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
self.__log_transaction(f"Withdraw: -{
amount}")
else:
raise ValueError("Invalid amount")
def __log_transaction(self, message): # 私有方法
print(f"[{
self.owner}] {
message}")
@property
def balance(self):
return f"${
self.__balance:.2f}"
# 使用示例
account = BankAccount("Alice", 1000)
account.deposit(500) # [Alice] Deposit: +500
account.withdraw(200) # [Alice] Withdraw: -200
print(account.balance) # $1300.00
封装优势:
- 保护敏感数据(如
__balance
) - 隐藏内部实现(如交易日志记录)
- 提供标准接口(存款/取款方法)
2.2 继承(Inheritance)
游戏开发案例:角色系统
class GameCharacter:
def __init__(self, name, health):
self.name = name
self.health = health
def take_damage(self, damage):
self.health = max(0, self.health - damage)
print(f"{
self.name}受到{
damage}点伤害")
def __str__(self):
return f"{
self.name}(生命值:{
self.health})"
class Warrior(GameCharacter):
def __init__(self, name, health, armor):
super().__init__(name, health)
self.armor = armor
def take_damage(self, damage): # 方法重写