魔法方法
记录学习
基本的魔法方法
方法 | 含义 |
---|---|
__new__(cls[, ...]) | 在对象实例化时调用,用于创建对象 |
__init__(self[, ...]) | 初始化方法,在对象创建后调用 |
__del__(self) | 析构器,在对象销毁时调用 |
__call__(self[, args...]) | 允许对象像函数一样被调用 |
__len__(self) | 定义对象被 len() 调用时的行为 |
__repr__(self) | 定义对象被 repr() 调用时的行为 |
__str__(self) | 定义对象被 str() 调用时的行为 |
__bytes__(self) | 定义对象被 bytes() 调用时的行为 |
__hash__(self) | 定义对象被 hash() 调用时的行为 |
__bool__(self) | 定义对象被 bool() 调用时的行为 |
__format__(self, format_spec) | 定义对象被 format() 调用时的行为 |
属性相关
方法 | 含义 |
---|---|
__getattr__(self, name) | 定义访问不存在属性时的行为 |
__getattribute__(self, name) | 定义属性被访问时的行为 |
__setattr__(self, name, value) | 定义设置属性时的行为 |
__delattr__(self, name) | 定义删除属性时的行为 |
__dir__(self) | 定义 dir() 被调用时的行为 |
__get__(self, instance, owner) | 定义描述符的值被获取时的行为 |
__set__(self, instance, value) | 定义描述符的值被改变时的行为 |
__delete__(self, instance) | 定义描述符的值被删除时的行为 |
比较操作符
方法 | 含义 |
---|---|
__lt__(self, other) | 定义小于号的行为:< |
__le__(self, other) | 定义小于等于号的行为:<= |
__eq__(self, other) | 定义等于号的行为:== |
__ne__(self, other) | 定义不等号的行为:!= |
__gt__(self, other) | 定义大于号的行为:> |
__ge__(self, other) | 定义大于等于号的行为:>= |
算数运算符
方法 | 含义 |
---|---|
__add__(self, other) | 定义加法的行为:+ |
__sub__(self, other) | 定义减法的行为:- |
__mul__(self, other) | 定义乘法的行为:* |
__truediv__(self, other) | 定义真除法的行为:/ |
__floordiv__(self, other) | 定义整除法的行为:// |
__mod__(self, other) | 定义取模的行为:% |
__divmod__(self, other) | 定义 divmod() 的行为 |
__pow__(self, other[, modulo]) | 定义 ** 运算的行为 |
反运算
方法 | 含义 |
---|---|
__radd__(self, other) | 右侧加法操作的行为 |
__rsub__(self, other) | 右侧减法操作的行为 |
__rmul__(self, other) | 右侧乘法操作的行为 |
__rtruediv__(self, other) | 右侧真除法操作的行为 |
__rfloordiv__(self, other) | 右侧整除法操作的行为 |
__rmod__(self, other) | 右侧取模操作的行为 |
__rdivmod__(self, other) | 右侧 divmod() 操作的行为 |
__rpow__(self, other) | 右侧幂运算的行为 |
增量赋值运算
方法 | 含义 |
---|---|
__iadd__(self, other) | 定义加法赋值的行为:+= |
__isub__(self, other) | 定义减法赋值的行为:-= |
__imul__(self, other) | 定义乘法赋值的行为:*= |
__itruediv__(self, other) | 定义真除法赋值的行为:/= |
__ifloordiv__(self, other) | 定义整除赋值的行为://= |
__imod__(self, other) | 定义取模赋值的行为:%= |
__ipow__(self, other[, modulo]) | 定义幂运算赋值的行为:**= |
一元操作符
方法 | 含义 |
---|---|
__pos__(self) | 正号的行为:+x |
__neg__(self) | 负号的行为:-x |
__abs__(self) | abs() 调用时的行为 |
__invert__(self) | 按位求反的行为:~x |
类型转换
方法 | 含义 |
---|---|
__complex__(self) | complex() 调用时的行为 |
__int__(self) | int() 调用时的行为 |
__float__(self) | float() 调用时的行为 |
__round__(self[, n]) | round() 调用时的行为 |
__index__(self) | 在切片表达式中的整形强制转换 |
上下文管理
方法 | 含义 |
---|---|
__enter__(self) | 定义 with 语句时的初始化行为 |
__exit__(self, exc_type, exc_value, traceback) | 定义上下文管理器结束时的行为 |
容器类型
方法 | 含义 |
---|---|
__len__(self) | 定义 len() 调用时的行为 |
__getitem__(self, key) | 定义获取元素的行为 |
__setitem__(self, key, value) | 定义设置元素的行为 |
__delitem__(self, key) | 定义删除元素的行为 |
__iter__(self) | 定义迭代元素的行为 |
__reversed__(self) | 定义 reversed() 调用时的行为 |
__contains__(self, item) | 定义成员测试运算符的行为 |