Python数据模型中的特殊(魔术)方法

  • __init__(self):构造方法,在创建对象时调用。
  • __str__(self):返回一个可读字符串表示。
  • __repr__(self):返回一个可读字符串表示,通常用于调试。
  • __len__(self):返回对象的长度。
  • __getitem__(self, key):返回对象的项,例如obj[key]
  • __setitem__(self, key, value):设置对象的项,例如obj[key] = value
  • __delitem__(self, key):删除对象的项,例如del obj[key]
  • __add__(self, other):对象的加法,例如obj + other
  • __sub__(self, other):对象的减法,例如obj - other
  • __mul__(self, other):对象的乘法,例如obj * other
  • __truediv__(self, other):对象的除法,例如obj / other
  • __lt__(self, other):小于运算符,例如obj < other
  • __le__(self, other):小于等于运算符,例如obj <= other
  • __eq__(self, other):等于运算符,例如obj == other
  • __ne__(self, other):不等于运算符,例如obj != other
  • __gt__(self, other):大于运算符,例如obj > other
  • __ge__(self, other):大于等于运算符,例如obj >= other
  • __call__(self, *args, **kwargs):对象的函数调用,例如obj(*args, **kwargs)
  • __iter__(self):返回一个迭代器。
  • __next__(self):返回迭代器的下一个项。
posted @ 2023-08-10 00:06  清宵入梦  阅读(19)  评论(0)    收藏  举报