当前位置: 首页 > news >正文

Python 面向对象三大特性深度解析

面向对象三大特性

一、封装(Encapsulation)

1. 私有化实现

class BankAccount:
    def __init__(self, account_holder, balance=0):
        self.__holder = account_holder  # 双下划线私有属性
        self.__balance = balance
    
    # 公有方法访问私有属性
    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount
            print(f"存款成功,当前余额:{self.__balance}")
    
    def get_balance(self):
        return self.__balance

# 使用示例
account = BankAccount("Alice", 1000)
account.deposit(500)  # 正常操作
print(account.__balance)  # 报错:AttributeError

2. 属性装饰器

class Temperature:
    def __init__(self, celsius):
        self._celsius = celsius  # 保护属性
    
    @property
    def celsius(self):
        return self._celsius
    
    @celsius.setter
    def celsius(self, value):
        if value < -273.15:
            raise ValueError("温度不能低于绝对零度")
        self._celsius = value
    
    @property
    def fahrenheit(self):
        return self._celsius * 9/5 + 32

# 使用示例
temp = Temperature(25)
print(temp.fahrenheit)  # 77.0
temp.celsius = 30       # 正常设置
temp.celsius = -300     # ValueError

二、继承(Inheritance)

1. 单继承示例


class Animal:
    def __init__(self, name):
        self.name = name
    
    def speak(self):
        raise NotImplementedError("子类必须实现此方法")

class Dog(Animal):
    def speak(self):
        return "汪汪!"
    
    def fetch(self, item):
        print(f"{self.name} 捡回了 {item}")

class Cat(Animal):
    def speak(self):
        return "喵~"

# 使用示例
dog = Dog("Buddy")
print(dog.speak())  # 汪汪!
dog.fetch("球")     # Buddy 捡回了 球

cat = Cat("Kitty")
print(cat.speak())  # 喵~

2. 多继承与MRO


class Camera:
    def take_photo(self):
        print("拍照中...")

class Phone:
    def make_call(self, number):
        print(f"正在拨打:{number}")

class SmartPhone(Camera, Phone):
    def run_app(self, app_name):
        print(f"运行 {app_name}")

# 查看方法解析顺序
print(SmartPhone.mro())
# [<class '__main__.SmartPhone'>, 
#  <class '__main__.Camera'>, 
#  <class '__main__.Phone'>, 
#  <class 'object'>]

# 使用示例
phone = SmartPhone()
phone.take_photo()  # 拍照中...
phone.make_call(110) # 正在拨打:110

三、多态(Polymorphism)

1. 方法重写实现多态

class Shape:
    def area(self):
        pass

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius
    
    def area(self):
        return 3.14 * self.radius ** 2

class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height
    
    def area(self):
        return self.width * self.height

# 多态调用
shapes = [Circle(5), Rectangle(4, 6)]
for shape in shapes:
    print(f"图形面积:{shape.area()}")

2. 鸭子类型实现多态


class PDFGenerator:
    def generate(self, data):
        print("生成PDF文档:", data)

class HTMLGenerator:
    def generate(self, data):
        print("生成HTML页面:", data)

def export_data(exporter, data):
    exporter.generate(data)

# 调用示例
export_data(PDFGenerator(), "报表数据")  # 生成PDF文档
export_data(HTMLGenerator(), "产品目录") # 生成HTML页面

四、综合实战案例

员工管理系统

class Employee:
    def __init__(self, name, emp_id):
        self.__name = name
        self.__emp_id = emp_id
    
    @property
    def name(self):
        return self.__name
    
    def calculate_salary(self):
        raise NotImplementedError

class FullTimeEmployee(Employee):
    def __init__(self, name, emp_id, monthly_salary):
        super().__init__(name, emp_id)
        self.__monthly_salary = monthly_salary
    
    def calculate_salary(self):
        return self.__monthly_salary

class PartTimeEmployee(Employee):
    def __init__(self, name, emp_id, hourly_rate, hours):
        super().__init__(name, emp_id)
        self.hourly_rate = hourly_rate
        self.hours = hours
    
    def calculate_salary(self):
        return self.hourly_rate * self.hours

# 使用示例
employees = [
    FullTimeEmployee("张三", "FT001", 15000),
    PartTimeEmployee("李四", "PT001", 100, 80)
]

for emp in employees:
    print(f"{emp.name} 薪资:{emp.calculate_salary()}")

五、最佳实践与注意事项

  1. 封装原则

    • 使用最少公开原则(最小化公有接口)
    • 优先使用属性装饰器而不是直接暴露属性
  2. 继承规范

    • 避免超过三层的继承链
    • 慎用多继承,优先使用组合
    • 使用 super() 正确调用父类方法
  3. 多态实现

    • 遵循里氏替换原则(子类可替换父类)
    • 使用抽象基类(ABC)强制接口实现

from abc import ABC, abstractmethod

class DatabaseConnector(ABC):
    @abstractmethod
    def connect(self):
        pass
  1. 常见错误
# 错误:忘记调用super().__init__
class SubClass(Parent):
    def __init__(self, param):
        self.param = param  # 父类初始化未执行

通过本教程的实践,您已经掌握面向对象编程的核心特性。建议进一步学习:

  • 魔术方法(如 str, add
  • 元类编程(metaclass)
  • 设计模式(工厂模式、观察者模式等)

相关文章:

  • C#与西门子PLC的六大通信库
  • VSCode中搜索插件显示“提取扩展时出错。Failed to fetch”问题解决!
  • java基础--序列化与反序列化的概念是什么?
  • 大数据学习(80)-数仓分层
  • Spring 三级缓存能不能解决循环依赖?
  • 概率预测之NGBoost(Natural Gradient Boosting)回归和分位数(Quantile Regression)回归
  • KNN算法
  • Spring Boot中接口数据字段为 Long 类型时,前端number精度丢失问题解决方案
  • Vue入门
  • 油候插件、idea、VsCode插件推荐(自用)
  • 申请使用受限权限
  • 深入解析:Nginx+Keepalived实现双机热备架构
  • 《汽车电器与电子技术》第四次作业
  • Prometheus Exporter系列-Postgres_Exporter一键部署
  • JavaScript基础-节点操作
  • StarRocks 升级注意事项
  • Azure Delta Lake、Databricks和Event Hubs实现实时欺诈检测
  • HTML应用指南:利用GET请求获取猫眼电影日票房信息——以哪吒2为例
  • (每日一道算法题)交易逆序对的总数
  • SAP Commerce(Hybris)PCM模块(一):商品批量导入导出
  • 游戏论|暴君无道,吊民伐罪——《苏丹的游戏》中的政治
  • A股三大股指低收:银行股再度走强,两市成交11920亿元
  • 壹基金发布2024年度报告,公益项目惠及937万人次
  • 丰田汽车:美国关税或导致4、5月损失1800亿日元,新财年净利润下滑三成
  • 东亚社会的“苦难诗学”:从《苦尽柑来遇见你》说起
  • 优化网络营商环境,上海严厉打击涉企网络谣言、黑灰产等违法犯罪