对象生命周期
| 方法 | 说明 |
|---|---|
| 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 |