python中的魔法方法
对象生命周期
| 方法 | 说明 |
|---|---|
| __new__(cls, …) | 创建实例(先于init) |
| __init__(self, …) | 初始化实例 |
| __del__(self) | 对象销毁 |
| __call__(self, …) | 让实例可调用 |
属性访问控制
| 方法 | 说明 |
|---|---|
| __getattr__(self, name) | 属性不存在时 |
| __getattribute__(self, name) | 所有属性访问 |
| __setattr__(self, name, value) | 设置属性 |
| __delattr__(self, name) | 删除属性 |
容器 / 集合行为
| 方法 | 说明 |
|---|---|
| __len__(self) | len(obj) |
| __getitem__(self, key) | obj[i] |
| __setitem__(self, key, val) | obj[i] = v |
| __delitem__(self, key) | del obj[i] |
| __iter__(self) | for x in obj |
| __contains__(self, item) | x in obj |
数值运算(算数 & 位运算)
| 方法 | 说明 |
|---|---|
| __add__(self, other) | + |
| __sub__(self, other) | - |
| __mul__(self, other) | * |
| _\truediv__(self, other) | / |
| __pow__(self, other) | ** |
| __neg__(self) | -obj |
比较与排序
| 方法 | 说明 |
|---|---|
| __eq__(self, other) | == |
| __ne__(self, other) | != |
| __lt__(self, other) | < |
| __le__(self, other) | <= |
| __gt__(self, other) | > |
| __ge__(self, other) | >= |
字符串与格式化
| 方法 | 说明 |
|---|---|
| __str__(self) | str(obj) |
| __repr__(self) | repr(obj) |
| __format__(self, fmt) | format(obj) |
| __\bytes__(self) | bytes(obj) |
上下文管理器
| 方法 | 说明 |
|---|---|
| __enter__(self) | with obj: |
| __exit__(self, *exc) | 退出上下文 |
序列化 / Pickle
| 方法 | 说明 |
|---|---|
| __reduce__(self) | pickle 重建 |
| __reduce_ex__(self) | pickle 协议扩展 |
| __getstate__(self) | 控制序列化 |
| __setstate__(self, state) | 控制反序列化 |
元类 & 类创建
| 方法 | 说明 |
|---|---|
| __prepare__(mcs, name, bases) | 准备命名空间 |
| __instancecheck__(cls, obj) | isinstance |
| __subclasscheck__(cls, sub) | issubclass |
描述符协议
| 方法 | 说明 |
|---|---|
| __get__(self, obj, cls) | 读属性 |
| __set__(self, obj, value) | 写属性 |
| __delete__(self, obj) | 删属性 |
常用但容易忽略
| 方法 | 说明 |
|---|---|
| __hash__(self) | hash(obj) |
| __bool__(self) | bool(obj) |
| __copy__(self) | copy.copy |
| __deepcopy__(self, memo) | copy.deepcopy |
