Python 类的魔术方法

Python 类中的魔术方法(特殊方法)可以分为以下详细类别,包含了常见方法及其用途和示例。所有内容基于 Python 3.12 版本。


一、对象生命周期

1. 构造与销毁
  • __new__(cls[, ...]): 创建实例(控制对象创建逻辑)。

    class Singleton:
        _instance = None
        def __new__(cls):
            if not cls._instance:
                cls._instance = super().__new__(cls)
            return cls._instance
    
  • __init__(self[, ...]): 初始化实例(设置初始属性)。

    class Point:
        def __init__(self, x, y):
            self.x, self.y = x, y
    
  • __del__(self): 对象销毁前的清理操作(慎用,不可靠)。

    class Resource:
        def __del__(self):
            print("释放资源")
    

二、对象表示与格式化

2. 字符串表示
  • __str__(self): 返回用户友好字符串(str(obj)print(obj))。

    class Person:
        def __str__(self):
            return "Person对象"
    
  • __repr__(self): 返回明确的对象表示(用于调试或交互式环境)。

    class Vector:
        def __repr__(self):
            return f"Vector({self.x}, {self.y})"
    
  • __bytes__(self): 返回对象的字节表示(bytes(obj))。

    class Data:
        def __bytes__(self):
            return b"binary data"
    
  • __format__(self, format_spec): 自定义格式化输出(format()f"{obj:spec}")。

    class Temperature:
        def __format__(self, spec):
            return f"{self.value}°C"
    

三、容器类型模拟

3. 序列/映射行为
  • __len__(self): 返回容器长度(len(obj))。

    class MyList:
        def __len__(self):
            return 10
    
  • __getitem__(self, key): 获取元素(obj[key])。

    class MyDict:
        def __getitem__(self, key):
            return self.data[key]
    
  • __setitem__(self, key, value): 设置元素(obj[key] = value)。

    class MyList:
        def __setitem__(self, idx, value):
            self.data[idx] = value
    
  • __delitem__(self, key): 删除元素(del obj[key])。

  • __contains__(self, item): 检查成员存在性(item in obj)。

    class Range:
        def __contains__(self, item):
            return self.start <= item <= self.end
    
  • __reversed__(self): 反向迭代(reversed(obj))。


四、比较与哈希

4. 比较操作符
  • __eq__(self, other): ==

  • __lt__(self, other): <

  • __le__(self, other): <=

  • __gt__(self, other): >

  • __ge__(self, other): >=

  • __ne__(self, other): !=

    class Money:
        def __eq__(self, other):
            return self.amount == other.amount
    
5. 哈希与布尔
  • __hash__(self): 定义对象的哈希值(hash(obj))。

    class User:
        def __hash__(self):
            return hash(self.username)
    
  • __bool__(self): 定义真值测试(if obj:)。

    class NonZero:
        def __bool__(self):
            return self.value != 0
    

五、算术运算

6. 基本运算符
  • __add__(self, other): +
  • __sub__(self, other): -
  • __mul__(self, other): *
  • __truediv__(self, other): /
  • __floordiv__(self, other): //
  • __mod__(self, other): %
  • __pow__(self, other): **
7. 反向运算符(当左操作数不支持操作时调用)
  • __radd__(self, other): +
  • __rsub__(self, other): -
  • 其他类似:__rmul__, __rtruediv__ 等。
8. 增量赋值
  • __iadd__(self, other): +=
  • __isub__(self, other): -=
  • 其他类似:__imul__, __idiv__ 等。
9. 其他数学操作
  • __neg__(self): -obj
  • __pos__(self): +obj
  • __abs__(self): abs(obj)
  • __round__(self, n): round(obj)

六、类型转换

10. 显式类型转换
  • __int__(self): int(obj)
  • __float__(self): float(obj)
  • __complex__(self): complex(obj)
  • __index__(self): 转换为整数(用于切片或 bin()/hex())。

七、上下文管理

11. with 语句
  • __enter__(self): 进入上下文(返回资源)。

  • __exit__(self, exc_type, exc_val, traceback): 退出上下文(处理异常)。

    class FileContext:
        def __enter__(self):
            self.file = open("file.txt")
            return self.file
        def __exit__(self, *args):
            self.file.close()
    

八、属性控制

12. 属性访问
  • __getattr__(self, name): 访问未定义属性时调用。

    class DynamicAttributes:
        def __getattr__(self, name):
            return f"属性 {name} 不存在"
    
  • __getattribute__(self, name): 访问所有属性时调用(需谨慎使用)。

  • __setattr__(self, name, value): 设置属性时调用。

    class Validated:
        def __setattr__(self, name, value):
            if name == "age" and value < 0:
                raise ValueError("年龄不能为负")
            super().__setattr__(name, value)
    
  • __delattr__(self, name): 删除属性时调用。

  • __dir__(self): 返回属性列表(dir(obj))。


九、可调用对象

13. 函数调用行为
  • __call__(self[, ...]): 使实例可像函数一样调用。

    class Adder:
        def __call__(self, a, b):
            return a + b
    add = Adder()
    add(2, 3)  # 输出 5
    

十、迭代器协议

14. 迭代与生成
  • __iter__(self): 返回迭代器对象(通常返回 self)。

  • __next__(self): 返回下一个元素(无元素时抛出 StopIteration)。

    class CountDown:
        def __init__(self, start):
            self.current = start
        def __iter__(self):
            return self
        def __next__(self):
            if self.current <= 0:
                raise StopIteration
            self.current -= 1
            return self.current + 1
    

十一、描述符协议

15. 描述符控制
  • __get__(self, instance, owner): 获取描述符的值。

  • __set__(self, instance, value): 设置描述符的值。

  • __delete__(self, instance): 删除描述符的值。

    class Field:
        def __get__(self, instance, owner):
            return instance.__dict__[self.name]
        def __set__(self, instance, value):
            instance.__dict__[self.name] = value
        def __set_name__(self, owner, name):
            self.name = name
    

十二、异步支持

16. 协程与异步迭代
  • __await__(self): 返回迭代器(await obj)。

  • __aiter__(self): 返回异步迭代器。

  • __anext__(self): 异步返回下一个元素。

  • __aenter__(self)__aexit__(self): 异步上下文管理。

    class AsyncReader:
        async def __aenter__(self):
            await self.connect()
            return self
        async def __aexit__(self, *args):
            await self.close()
    

十三、类元编程

17. 类行为控制
  • __init_subclass__(cls): 子类初始化时的钩子。

    class Base:
        def __init_subclass__(cls, **kwargs):
            print(f"子类 {cls} 被创建")
    
  • __class_getitem__(cls, item): 支持泛型类型(如 list[int])。

  • __set_name__(self, owner, name): 描述符被分配给类属性时调用(见描述符示例)。


十四、其他杂项

18. 序列化与拷贝
  • __getstate__(self): 定义 pickle 序列化的状态。

  • __setstate__(self, state): 反序列化时恢复状态。

  • __copy__(self)__deepcopy__(self, memo): 控制 copy 模块的行为。

19. 路径表示
  • __fspath__(self): 返回文件系统路径(os.fspath() 使用)。

    class PathWrapper:
        def __fspath__(self):
            return "/path/to/file"
    
20. 模式匹配(Python 3.10+)
  • __match_args__: 定义类在模式匹配中的位置参数。

    class Point:
        __match_args__ = ("x", "y")
        def __init__(self, x, y):
            self.x, self.y = x, y
    

你可能感兴趣的:(python技巧分享,python,开发语言)