"""
面向对象编程三大特性精讲
========================
面向对象编程(Object-Oriented Programming, OOP)是一种将程序视为一系列“对象”交互的编程范式,核心是通过对象(包含数据和操作)
来模拟现实世界,提升代码的复用性、可维护性和扩展性。以下是零基础解释:
核心概念(用生活比喻)
对象:独立的实体,如“手机”(拥有品牌、电量等属性,能打电话、拍照等方法)。
类:对象的蓝图或模板,如“手机设计图纸”,定义了所有手机的共同特征。
三大特性:
封装:隐藏内部细节(如手机内部电路),只暴露安全接口(如电源按钮)。
继承:子类复用父类功能(如智能手机继承基础手机的功能,并新增触屏)。
多态:同一接口不同实现(如“播放”按钮,在音乐App播歌,在视频App播影片)。
总述:面向对象编程(OOP)如同组装乐高积木
三大特性:
1️⃣ 封装 → 把零件装进盒子(隐藏细节)
2️⃣ 继承 → 复用基础积木(扩展功能)
3️⃣ 多态 → 相同接口不同效果(灵活变化)
"""
"""
面向对象编程三大特性精讲(双例版)
========================
总述:面向对象编程(OOP)如同建造模块化城市
三大特性协同工作:
┌───────────────┬───────────────┬───────────────┐
│ 封装 │ 继承 │ 多态 │
├───────────────┼───────────────┼───────────────┤
│ 保护数据安全 │ 复用代码逻辑 │ 统一接口操作 │
│ 隐藏实现细节 │ 扩展系统功能 │ 实现灵活变化 │
└───────────────┴───────────────┴───────────────┘
"""
# ===================== 分:特性详解(每个特性两个例子) =====================
# 特性1:封装(保护数据)
"""
封装原则:隐藏内部实现细节,仅暴露安全接口
"""
# 例子1:银行账户系统
class BankAccount:
def __init__(self, owner, initial_balance=0):
self.owner = owner # 公开属性
self.__balance = initial_balance # 私有属性(双下划线)
# 存款接口
def deposit(self, amount):
if amount > 0:
self.__balance += amount
print(f"存入{amount}元,当前余额:{self.__balance}元")
else:
print("存款金额必须大于0")
# 取款接口
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
print(f"取出{amount}元,当前余额:{self.__balance}元")
else:
print("取款金额无效或余额不足")
# 余额查询接口
def get_balance(self):
return self.__balance
# 使用银行账户
alice_account = BankAccount("Alice", 1000)
alice_account.deposit(500) # 存入500元,当前余额:1500元
alice_account.withdraw(200) # 取出200元,当前余额:1300元
# alice_account.__balance = 9999 # 无法直接修改私有属性(保护数据安全)
# 例子2:温度控制器
class TemperatureController:
def __init__(self):
self.__current_temp = 25 # 私有属性
self.__max_temp = 35 # 私有属性
# 安全设置温度接口
def set_temperature(self, temp):
if 18 <= temp <= self.__max_temp:
self.__current_temp = temp
print(f"温度已设置为{temp}℃")
else:
print(f"温度设置无效,必须在18℃到{self.__max_temp}℃之间")
def get_temperature(self):
return self.__current_temp
# 使用温度控制器
thermo = TemperatureController()
thermo.set_temperature(22) # 温度已设置为22℃
thermo.set_temperature(40) # 温度设置无效,必须在18℃到35℃之间
# 特性2:继承(代码复用)
"""
继承原则:子类复用父类功能,并扩展新特性
"""
# 例子1:几何图形体系
class Shape: # 父类
def __init__(self, color):
self.color = color
def area(self):
pass # 抽象方法
def describe(self):
print(f"这是一个{self.color}的图形")
class Circle(Shape): # 子类
def __init__(self, color, radius):
super().__init__(color) # 调用父类构造
self.radius = radius
# 重写面积计算方法
def area(self):
return 3.14 * self.radius * self.radius
# 新增方法
def circumference(self):
return 2 * 3.14 * self.radius
class Rectangle(Shape): # 另一个子类
def __init__(self, color, width, height):
super().__init__(color)
self.width = width
self.height = height
def area(self):
return self.width * self.height
# 使用几何图形体系
blue_circle = Circle("蓝色", 5)
red_rect = Rectangle("红色", 4, 6)
blue_circle.describe() # 这是一个蓝色的图形(继承父类方法)
print(f"圆形面积: {blue_circle.area()}") # 圆形面积: 78.5(子类实现)
print(f"矩形面积: {red_rect.area()}") # 矩形面积: 24(子类实现)
# 例子2:员工管理系统
class Employee:
def __init__(self, name, id):
self.name = name
self.id = id
def calculate_salary(self):
return 5000 # 基础薪资
class Manager(Employee):
def __init__(self, name, id, bonus):
super().__init__(name, id)
self.bonus = bonus
# 重写薪资计算方法
def calculate_salary(self):
base = super().calculate_salary()
return base + self.bonus
class Developer(Employee):
def __init__(self, name, id, overtime_hours):
super().__init__(name, id)
self.overtime_hours = overtime_hours
def calculate_salary(self):
base = super().calculate_salary()
return base + self.overtime_hours * 100
# 使用员工体系
tom = Manager("Tom", "M001", 3000)
alice = Developer("Alice", "D001", 10)
print(f"经理薪资: {tom.calculate_salary()}") # 经理薪资: 8000
print(f"开发薪资: {alice.calculate_salary()}") # 开发薪资: 6000
# 特性3:多态(接口统一)
"""
多态原则:不同对象对相同方法名有不同实现
"""
# 例子1:多媒体播放系统
class MediaPlayer:
def play(self):
pass # 抽象方法
class AudioPlayer(MediaPlayer):
def play(self):
print("播放音频:MP3音乐")
class VideoPlayer(MediaPlayer):
def play(self):
print("播放视频:高清影片")
class StreamingPlayer(MediaPlayer):
def play(self):
print("流媒体播放:在线直播")
# 多态播放函数
def start_playback(player):
player.play() # 统一接口
# 使用播放系统
music_player = AudioPlayer()
movie_player = VideoPlayer()
live_stream = StreamingPlayer()
start_playback(music_player) # 播放音频:MP3音乐
start_playback(movie_player) # 播放视频:高清影片
start_playback(live_stream) # 流媒体播放:在线直播
# 例子2:支付系统
class PaymentMethod:
def process_payment(self, amount):
pass
class CreditCard(PaymentMethod):
def process_payment(self, amount):
print(f"信用卡支付 {amount}元:输入卡号和安全码")
class Alipay(PaymentMethod):
def process_payment(self, amount):
print(f"支付宝支付 {amount}元:扫描二维码")
class WechatPay(PaymentMethod):
def process_payment(self, amount):
print(f"微信支付 {amount}元:确认支付密码")
# 统一支付接口
def checkout(payment_method, amount):
payment_method.process_payment(amount)
# 使用支付系统
visa = CreditCard()
alipay = Alipay()
wechat = WechatPay()
checkout(visa, 299) # 信用卡支付 299元:输入卡号和安全码
checkout(alipay, 150) # 支付宝支付 150元:扫描二维码
checkout(wechat, 80) # 微信支付 80元:确认支付密码
# ===================== 总:三大特性综合应用 =====================
"""
智能家居系统升级版(集成封装、继承、多态)
1. 封装:设备状态设为私有
2. 继承:设备基类扩展出多种设备
3. 多态:统一控制接口操作不同设备
"""
# 设备基类(封装)
class SmartDevice:
def __init__(self, name):
self.name = name
self.__power = False # 私有属性
def turn_on(self):
self.__power = True
print(f"{self.name}已启动")
def turn_off(self):
self.__power = False
print(f"{self.name}已关闭")
def status(self):
return "运行中" if self.__power else "已关机"
# 照明设备(继承+封装)
class SmartLight(SmartDevice):
def __init__(self, name):
super().__init__(name)
self.__brightness = 50
# 封装亮度控制
def set_brightness(self, level):
if 0 <= level <= 100:
self.__brightness = level
print(f"亮度设置为{level}%")
# 多态:状态报告实现
def status(self):
base = super().status()
return f"{base},亮度{self.__brightness}%" if self.__power else base
# 窗帘设备(继承+封装)
class SmartCurtain(SmartDevice):
def __init__(self, name):
super().__init__(name)
self.__open_percent = 0
def set_open(self, percent):
if 0 <= percent <= 100:
self.__open_percent = percent
status = "开启" if percent > 0 else "关闭"
print(f"窗帘{status},开合度{percent}%")
# 多态:状态报告实现
def status(self):
base = super().status()
return f"{base},开合度{self.__open_percent}%" if self.__power else base
# 多态控制中心
def home_scene(scene_name, devices):
print(f"\n=== 执行场景:{scene_name} ===")
for device in devices:
device.turn_on()
print(f"{device.name}状态: {device.status()}")
# 创建设备
bedroom_light = SmartLight("卧室主灯")
living_curtain = SmartCurtain("客厅窗帘")
# 早晨场景
home_scene("早安模式", [bedroom_light, living_curtain])
bedroom_light.set_brightness(80)
living_curtain.set_open(70)
# 夜晚场景
home_scene("晚安模式", [bedroom_light, living_curtain])
bedroom_light.set_brightness(20)
living_curtain.set_open(0)
for device in [bedroom_light, living_curtain]:
device.turn_off()
"""
输出示例:
=== 执行场景:早安模式 ===
卧室主灯已启动
卧室主灯状态: 运行中,亮度50%
客厅窗帘已启动
客厅窗帘状态: 运行中,开合度0%
亮度设置为80%
窗帘开启,开合度70%
=== 执行场景:晚安模式 ===
卧室主灯已启动
卧室主灯状态: 运行中,亮度80%
客厅窗帘已启动
客厅窗帘状态: 运行中,开合度70%
亮度设置为20%
窗帘关闭,开合度0%
卧室主灯已关闭
客厅窗帘已关闭
"""
"""
终极总结:
1️⃣ 封装 → 保险箱机制
• 保护核心数据(私有属性)
• 提供安全操作通道(公开方法)
2️⃣ 继承 → 家族树机制
• 复用父类功能(减少重复代码)
• 扩展新特性(添加新方法)
• 定制化功能(方法重写)
3️⃣ 多态 → 万能适配器
• 统一接口标准(方法名一致)
• 不同对象不同实现(多态方法)
• 系统扩展性强(新增类无缝接入)
协同效应:
封装保证数据安全 → 继承保证高效扩展 → 多态保证灵活操作
"""
# ===================== OOP最佳实践指南 =====================
"""
面向对象编程高效开发守则
1️⃣ 设计原则:SOLID基石
- S: 单一职责原则 → 每个类只做一件事
- O: 开闭原则 → 对扩展开放,对修改关闭
- L: 里氏替换原则 → 子类必须能替换父类
- I: 接口隔离原则 → 多个专用接口优于单一臃肿接口
- D: 依赖倒置原则 → 依赖抽象而非具体实现
2️⃣ 命名规范(Pythonic风格)
- 类名:大驼峰式 → SmartDevice
- 方法名:小写蛇形 → get_current_status()
- 私有成员:双下划线前缀 → __internal_counter
- 保护成员:单下划线前缀 → _temp_value
3️⃣ 继承使用准则
- 优先使用组合而非继承("has-a" > "is-a")
- 避免超过3层的继承链
- 抽象基类(ABC)定义接口契约
"""
# === 最佳实践代码示例 ===
# 实践1:遵循单一职责原则
class UserAuthenticator: # 只负责认证
def login(self, username, password):
# 验证逻辑
print(f"{username}登录成功")
return True
class UserDataStorage: # 只负责存储
def save_profile(self, user_data):
# 存储逻辑
print("用户资料已保存")
# 实践2:开闭原则应用
from abc import ABC, abstractmethod
class ReportGenerator(ABC): # 抽象基类(对扩展开放)
@abstractmethod
def generate(self):
pass
class PDFReport(ReportGenerator): # 新增格式无需修改基类
def generate(self):
print("生成PDF格式报告")
class ExcelReport(ReportGenerator):
def generate(self):
print("生成Excel格式报告")
# 可根据需求扩展新报告类型
class HTMLReport(ReportGenerator):
def generate(self):
print("生成HTML网页报告")
# 实践3:组合优于继承
class Engine: # 独立引擎类
def start(self):
print("引擎启动")
class MusicSystem:
def play(self):
print("播放音乐")
class Car: # 通过组合复用功能
def __init__(self):
self.engine = Engine()
self.audio = MusicSystem()
def drive(self):
self.engine.start()
print("车辆行驶")
def entertainment(self):
self.audio.play()
# 使用组合
my_car = Car()
my_car.drive() # 引擎启动 → 车辆行驶
my_car.entertainment() # 播放音乐
# 实践4:依赖倒置原则
class Switchable(ABC): # 抽象接口
@abstractmethod
def turn_on(self):
pass
@abstractmethod
def turn_off(self):
pass
class LightBulb(Switchable): # 具体实现
def turn_on(self):
print("电灯亮起")
def turn_off(self):
print("电灯关闭")
class Fan(Switchable):
def turn_on(self):
print("风扇转动")
def turn_off(self):
print("风扇停止")
# 高层模块依赖抽象
class ElectricSwitch:
def __init__(self, device: Switchable): # 依赖抽象接口
self.device = device
def operate(self, state):
if state == "on":
self.device.turn_on()
else:
self.device.turn_off()
# 可替换不同设备
lamp_switch = ElectricSwitch(LightBulb())
lamp_switch.operate("on") # 电灯亮起
fan_switch = ElectricSwitch(Fan())
fan_switch.operate("on") # 风扇转动
# 实践5:防御性编程技巧
class TemperatureSensor:
def __init__(self, min_temp=-20, max_temp=60):
self.min = min_temp
self.max = max_temp
self.__current = 25
@property
def current_temperature(self): # 使用属性保护
return self.__current
@current_temperature.setter
def current_temperature(self, value):
if not (self.min <= value <= self.max):
raise ValueError(f"温度值必须在{self.min}℃到{self.max}℃之间")
self.__current = value
# 安全使用
sensor = TemperatureSensor()
try:
sensor.current_temperature = 100 # 触发异常
except ValueError as e:
print(f"错误:{e}") # 错误:温度值必须在-20℃到60℃之间
"""
OOP黄金法则备忘卡:
┌───────────────────┬───────────────────────┬───────────────────┐
│ 设计原则 │ 代码示例 │ 违反后果 │
├───────────────────┼───────────────────────┼───────────────────┤
│ 单一职责 │ UserAuth独立认证类 │ 修改牵一发动全身 │
│ 开闭原则 │ 新增HTMLReport类 │ 每次新增修改基类 │
│ 里氏替换 │ Switchable统一接口 │ 子类破坏父类逻辑 │
│ 组合优于继承 │ Car包含Engine对象 │ 过深继承链难维护 │
│ 防御性编程 │ 温度范围校验 │ 非法状态导致崩溃 │
└───────────────────┴───────────────────────┴───────────────────┘
"""
优化下注释,在讲三大特性时,需要用what,how,why,这种格式来讲清楚,再通过两个例子
最新发布