Python 中的 `__xxx__` 特殊方法:介绍与使用(1)

简介

在 Python 中,__xxx__ 形式的方法被称为魔术方法或特殊方法。这些方法有特殊的名称和用途,通常用于实现某些内置操作。例如,__init__ 用于对象初始化,__add__ 用于实现加法操作。

初始化和表示

  • __init__: 初始化对象。

    python 复制代码
    class MyClass:
        def __init__(self, value):
            self.value = value
  • __repr____str__: 控制对象的字符串表示形式。

    python 复制代码
    class MyClass:
        def __repr__(self):
            return f"MyClass(value={self.value})"

算术运算

  • __add__: 实现加法。

    python 复制代码
    class MyClass:
        def __add__(self, other):
            return MyClass(self.value + other.value)
  • __sub__, __mul__, __truediv__, __floordiv__, __mod__, __pow__: 类似地,这些分别用于减法、乘法、除法、地板除、模运算和幂运算。

比较运算

  • __eq__: 实现等于比较。

    python 复制代码
    class MyClass:
        def __eq__(self, other):
            return self.value == other.value
  • __lt__, __le__, __gt__, __ge__, __ne__: 用于 <, <=, >, >=, != 比较。

容器类型模拟

  • __len__: 获取容器长度。

    python 复制代码
    class MyList:
        def __len__(self):
            return len(self.items)
  • __getitem__, __setitem__, __delitem__: 实现索引、切片和删除操作。

其他

  • __call__: 使对象可调用。

    python 复制代码
    class MyClass:
        def __call__(self, x):
            return self.value * x
  • __getattr__, __setattr__, __delattr__: 自定义属性访问。

注意事项

  • 魔术方法通常不需要直接调用,而是通过相应的内置函数或运算符触发。
  • 不是所有的魔术方法都需要实现,只有在需要特定功能时才去覆写相应的魔术方法。

总结

Python 的 __xxx__ 形式的特殊方法提供了一种非常灵活的方式来自定义对象的行为和操作。了解和掌握这些方法是提高 Python 编程水平的关键之一。

相关推荐
aqi0012 分钟前
15天学会AI应用开发(八)使用向量数据库实现RAG功能
人工智能·python·大模型·ai编程·ai应用
Csvn1 小时前
`functools.lru_cache` —— 一行代码搞定缓存加速
后端·python
金銀銅鐵18 小时前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup111 天前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi001 天前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵1 天前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf1 天前
Agent 流程编排
后端·python·agent
copyer_xyf1 天前
Agent RAG
后端·python·agent