魔法方法(了解)

魔法方法(了解)

在 Python 中,魔法方法(Magic Methods) 是一类特殊的类方法,它们以双下划线 __ 开头和结尾(如 __init____str__ 等)。这些方法允许你定义对象的行为,使得类的实例可以像内建类型一样进行操作。魔法方法是 Python 面向对象编程中非常强大的一部分。

下面是一些常见的魔法方法及其用途:

一、基本魔法方法

方法名 说明
__init__(self, ...) 构造函数,在创建对象时调用
__new__(cls, ...) 创建对象时最先调用的方法(用于控制对象的创建过程)
__del__(self) 析构函数,在对象被销毁时调用
__repr__(self) 返回对象的“官方”字符串表示,供调试器使用
__str__(self) 返回对象的可读字符串表示,用于 print()str()
__bytes__(self) 返回对象的字节流表示
__hash__(self) 支持哈希操作(例如用于放入 set 或 dict 的 key)
__bool__(self) 定义当对象被转换为布尔值时的行为
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return f"{self.name} ({self.age})"

    def __repr__(self):
        return f"Person(name='{self.name}', age={self.age})"

二、运算符重载相关魔法方法

方法名 对应操作
__add__(self, other) + 运算符
__sub__(self, other) - 运算符
__mul__(self, other) * 运算符
__truediv__(self, other) / 运算符
__floordiv__(self, other) // 运算符
__mod__(self, other) % 运算符
__pow__(self, other[, mod]) ** 运算符
__lt__(self, other) < 比较
__le__(self, other) <= 比较
__eq__(self, other) == 比较
__ne__(self, other) != 比较
__gt__(self, other) > 比较
__ge__(self, other) >= 比较
class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

    def __repr__(self):
        return f"Vector({self.x}, {self.y})"

三、容器相关魔法方法

方法名 说明
__len__(self) len(obj)
__getitem__(self, key) 获取元素,如 obj[key]
__setitem__(self, key, value) 设置元素,如 obj[key] = value
__delitem__(self, key) 删除元素,如 del obj[key]
__iter__(self) 返回一个迭代器
__next__(self) 实现迭代器协议
__contains__(self, item) 支持 in 操作符
class MyList:
    def __init__(self, data):
        self.data = data

    def __getitem__(self, index):
        return self.data[index]

    def __len__(self):
        return len(self.data)

四、属性访问与描述符魔法方法

方法名 说明
__getattr__(self, name) 当访问不存在的属性时调用
__getattribute__(self, name) 总是在访问属性时调用
__setattr__(self, name, value) 设置属性时调用
__delattr__(self, name) 删除属性时调用
__dir__(self) 返回属性列表
class MyClass:
    def __getattr__(self, name):
        return f"属性 {name} 不存在"

五、可调用对象魔法方法

方法名 说明
__call__(self, *args, **kwargs) 让类的实例像函数一样被调用
class Adder:
    def __call__(self, a, b):
        return a + b

adder = Adder()
print(adder(3, 4))  # 输出 7

六、上下文管理器魔法方法

方法名 说明
__enter__(self) 上下文开始时调用(如 with 块)
__exit__(self, exc_type, exc_val, exc_tb) 上下文结束时调用
class MyContext:
    def __enter__(self):
        print("进入上下文")
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("退出上下文")

with MyContext() as mc:
    print("执行中...")

七、其他常用魔法方法

方法名 说明
__copy__(self) 浅拷贝支持
__deepcopy__(self, memo) 深拷贝支持
__slots__ 限制类的属性,节省内存
__doc__ 类或方法的文档字符串
__module__ 类所属模块
__class__ 对象所属类

小结

  • 魔法方法让自定义类具有类似内置类型的特性。
  • 使用魔法方法可以使代码更简洁、更具 Pythonic 风格。
  • 注意不要滥用魔法方法,否则可能降低代码可读性。
posted on 2025-06-24 02:09  burgess0x  阅读(36)  评论(0)    收藏  举报