python的特殊方法

83 阅读2分钟

初始化和构造

  • __init__(self, ...): 类的初始化方法。
  • __new__(cls, ...): 类的构造方法,用于创建实例。
  • __del__(self): 当对象被删除时调用的析构方法。

字符串表示

  • __str__(self): 定义对象的可读字符串表示。
  • __repr__(self): 定义对象的官方字符串表示,通常可以用来重新创建对象。
  • __format__(self, format_spec): 定义当传递给 format() 函数时对象的行为。

容器类型方法

  • __len__(self): 定义当传递给 len() 函数时对象的行为。
  • __getitem__(self, key): 定义获取容器中元素的行为。
  • __setitem__(self, key, value): 定义设置容器中元素的行为。
  • __delitem__(self, key): 定义删除容器中元素的行为。
  • __iter__(self): 定义迭代容器中元素的行为。
  • __contains__(self, item): 定义 in 运算符的行为。

数值类型模拟

  • __add__(self, other): 加法运算符 + 的行为。
  • __sub__(self, other): 减法运算符 - 的行为。
  • __mul__(self, other): 乘法运算符 * 的行为。
  • __truediv__(self, other): 真除法运算符 / 的行为。
  • __floordiv__(self, other): 地板除法运算符 // 的行为。
  • __mod__(self, other): 求余运算符 % 的行为。
  • __pow__(self, other[, modulo]): 幂运算符 ** 的行为。
  • __and__(self, other): 与运算符 & 的行为。
  • __or__(self, other): 或运算符 | 的行为。
  • __xor__(self, other): 异或运算符 ^ 的行为。
  • __lshift__(self, other): 左移运算符 << 的行为。
  • __rshift__(self, other): 右移运算符 >> 的行为。

比较方法

  • __eq__(self, other): 等于运算符 == 的行为。
  • __ne__(self, other): 不等于运算符 != 的行为。
  • __lt__(self, other): 小于运算符 < 的行为。
  • __le__(self, other): 小于等于运算符 <= 的行为。
  • __gt__(self, other): 大于运算符 > 的行为。
  • __ge__(self, other): 大于等于运算符 >= 的行为。

属性访问

  • __getattr__(self, name): 定义当读取不存在的属性时的行为。
  • __setattr__(self, name, value): 定义当对属性赋值时的行为。
  • __delattr__(self, name): 定义当删除属性时的行为。
  • __getattribute__(self, name): 定义当获取任意属性的值时的行为。

上下文管理

  • __enter__(self): 定义进入与对象相关的运行时上下文时的行为。
  • __exit__(self, exc_type, exc_value, traceback): 定义退出与对象相关的运行时上下文时的行为。

反射

  • __call__(self, *args, **kwargs): 允许一个类的实例表现得像是函数,定义当实例被调用时的行为。

这些只是 Python 中特殊方法的一部分。特殊方法允许开发者定制类的行为,从而使得实例能够更自然地配合 Python 的内建操作和函数。想要了解更多特殊方法,可以查看 Python 的官方文档关于数据模型的章节