首页 / 知识库 / 0基础入门-阅读资料 / 0基础-python入门到精通

附录 B 常用魔术方法速查表

对象创建与销毁

方法触发时机说明
__new__(cls)创建实例返回新实例,很少重写
__init__(self)初始化实例设置实例属性
__del__(self)对象销毁析构方法,避免依赖

字符串表示

方法触发时机说明
__repr__(self)repr(obj)开发者表示,应无歧义
__str__(self)str(obj), print(obj)用户友好表示
__format__(self, spec)format(obj), f"{obj}"格式化输出
__bytes__(self)bytes(obj)字节串表示

比较运算

方法运算符说明
__eq__(self, other)==相等
__ne__(self, other)!=不等
__lt__(self, other)<小于
__le__(self, other)<=小于等于
__gt__(self, other)>大于
__ge__(self, other)>=大于等于
__hash__(self)hash(obj)哈希值
__bool__(self)bool(obj), if obj真值判断

算术运算

方法运算符反向就地
__add__+__radd____iadd__
__sub__-__rsub____isub__
__mul__*__rmul____imul__
__truediv__/__rtruediv____itruediv__
__floordiv__//__rfloordiv____ifloordiv__
__mod__%__rmod____imod__
__pow__**__rpow____ipow__
__matmul__@__rmatmul____imatmul__

一元运算

方法运算符
__neg__(self)-obj
__pos__(self)+obj
__abs__(self)abs(obj)
__invert__(self)~obj

位运算

方法运算符反向就地
__and__&__rand____iand__
__or__|__ror____ior__
__xor__^__rxor____ixor__
__lshift__<<__rlshift____ilshift__
__rshift__>>__rrshift____irshift__

类型转换

方法触发时机
__int__(self)int(obj)
__float__(self)float(obj)
__complex__(self)complex(obj)
__index__(self)切片索引、bin()hex()
__round__(self, n)round(obj, n)
__trunc__(self)math.trunc(obj)
__floor__(self)math.floor(obj)
__ceil__(self)math.ceil(obj)

容器协议

方法触发时机说明
__len__(self)len(obj)长度
__getitem__(self, key)obj[key]取值
__setitem__(self, key, val)obj[key] = val赋值
__delitem__(self, key)del obj[key]删除
__contains__(self, item)item in obj成员检测
__iter__(self)iter(obj), for x in obj返回迭代器
__next__(self)next(obj)下一个值
__reversed__(self)reversed(obj)反向迭代器
__missing__(self, key)dict[key] 键不存在时仅 dict 子类

属性访问

方法触发时机说明
__getattr__(self, name)属性未找到时兜底方法
__getattribute__(self, name)每次属性访问优先于 __getattr__
__setattr__(self, name, val)obj.attr = val属性赋值
__delattr__(self, name)del obj.attr删除属性
__dir__(self)dir(obj)属性列表

描述符

方法触发时机
__get__(self, obj, type)读取属性
__set__(self, obj, value)设置属性
__delete__(self, obj)删除属性
__set_name__(self, owner, name)类创建时

上下文管理

方法触发时机
__enter__(self)with 语句进入
__exit__(self, exc_type, exc_val, exc_tb)with 语句退出
__aenter__(self)async with 进入
__aexit__(self, ...)async with 退出

类创建与元编程

方法触发时机
__init_subclass__(cls)子类被创建时
__class_getitem__(cls, item)MyClass[int]
__prepare__(mcs, name, bases)类体执行前(元类)
__instancecheck__(cls, inst)isinstance()
__subclasscheck__(cls, sub)issubclass()

其他

方法触发时机
__call__(self, ...)obj(...)
__len__(self)len(obj)
__sizeof__(self)sys.getsizeof(obj)
__slots__声明固定属性(不是方法)
__dict__实例属性字典
__class__实例的类
__match_args__match-case 位置模式