python--面向对象(3)

一、常用魔术方法(特殊方法)

Python 中以 __ 开头和结尾的方法称为 "魔术方法",用于自定义对象的行为:

方法 作用 示例
__init__ 初始化实例 def __init__(self, name): ...
__str__ 打印实例时的字符串 def __str__(self): return f"Person({self.name})"
__repr__ 交互式解释器显示的字符串 def __repr__(self): return f"Person('{self.name}')"
__add__ 重载 + 运算符 def __add__(self, other): return self.age + other.age
__len__ 重载 len () 函数 def __len__(self): return len(self.name)

示例:

python 复制代码
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def __str__(self):
        return f"Person(name={self.name}, age={self.age})"
    
    def __add__(self, other):
        return self.age + other.age

p1 = Person("张三", 18)
p2 = Person("李四", 19)

print(p1)        # 输出:Person(name=张三, age=18)(调用 __str__)
print(p1 + p2)   # 输出:37(调用 __add__)

二、抽象类

抽象类是包含 "抽象方法" 的类,不能实例化,子类必须实现抽象方法(强制规范子类行为),需借助 abc 模块:

python 复制代码
from abc import ABCMeta, abstractmethod

# 抽象类:继承 ABCMeta
class Shape(metaclass=ABCMeta):
    # 抽象方法:只有定义,无实现
    @abstractmethod
    def area(self):
        pass

# 子类必须实现抽象方法
class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius
    
    def area(self):
        return 3.14 * self.radius **2

# shape = Shape()  # 报错:无法实例化抽象类
circle = Circle(5)
print(circle.area())  # 输出:78.5

三、组合:替代多继承的复用方式

组合是将 "其他类的实例" 作为当前类的属性,实现代码复用(比多继承更灵活):

python 复制代码
# 引擎类
class Engine:
    def run(self):
        print("引擎启动")

# 汽车类(组合引擎类)
class Car:
    def __init__(self):
        self.engine = Engine()  # 组合:将 Engine 实例作为属性
    
    def start(self):
        self.engine.run()
        print("汽车启动")

car = Car()
car.start()
# 输出:
# 引擎启动
# 汽车启动

四、核心总结

  1. 类与对象 :类是模板,对象是实例,self 指代当前实例;

  2. 属性:实例属性(独有)、类属性(共享);

  3. 方法 :实例方法(self)、类方法(@classmethod + cls)、静态方法(@staticmethod);

  4. 三大特性

    • 封装:私有属性 / 方法 + @property 隐藏细节;
    • 继承:class 子类(父类)super() 调用父类方法;
    • 多态:子类重写父类方法,统一接口调用;
  5. 进阶:魔术方法自定义对象行为,抽象类强制子类规范,组合替代多继承实现复用。

相关推荐
AI探索者13 小时前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者13 小时前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh15 小时前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅15 小时前
Python函数入门详解(定义+调用+参数)
python
曲幽16 小时前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时20 小时前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿1 天前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780512 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng82 天前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi2 天前
Chapter 2 - Python中的变量和简单的数据类型
python