| __new__(cls[, ...]) | 1. __new__ 是在一个对象实例化的时候所调用的第一个方法 2. 它的第一个参数是这个类,其他的参数是用来直接传递给 __init__ 方法 3. __new__ 决定是否要使用该 __init__ 方法,因为 __new__ 可以调用其他类的构造方法或者直接返回别的实例对象来作为本类的实例,如果 __new__ 没有返回实例对象,则 __init__ 不会被调用 4. __new__ 主要是用于继承一个不可变的类型比如一个 tuple 或者 string |
| __init__(self[, ...]) | 构造器,当一个实例被创建的时候调用的初始化方法 |
| __del__(self) | 析构器,当一个实例被销毁的时候调用的方法 |
| __getattr__(self, name) | 定义当用户试图获取一个不存在的属性时的行为 |
| __getattribute__(self, name) | 定义当该类的属性被访问时的行为 |
| __setattr__(self, name, value) | 定义当一个属性被设置时的行为 |
| __delattr__(self, name) | 定义当一个属性被删除时的行为 |
| __add__(self, other) | 定义加法的行为:+ |
| __sub__(self, other) | 定义减法的行为:- |
| __mul__(self, other) | 定义乘法的行为:* |
| __truediv__(self, other) | 定义真除法的行为:/ |
| __floordiv__(self, other) | 定义整数除法的行为:// |
| __mod__(self, other) | 定义取模算法的行为:% |
| __pow__(self, other[, modulo]) | 定义当被 power() 调用或 ** 运算时的行为 |
| __lshift__(self, other) | 定义按位左移位的行为:<< |
| __rshift__(self, other) | 定义按位右移位的行为:>> |
| __and__(self, other) | 定义按位与操作的行为:& |
| __xor__(self, other) | 定义按位异或操作的行为:^ |
| __or__(self, other) | 定义按位或操作的行为:| |
| __iadd__(self, other) | 定义赋值加法的行为:+= |
| __isub__(self, other) | 定义赋值减法的行为:-= |
| __imul__(self, other) | 定义赋值乘法的行为:*= |
| __itruediv__(self, other) | 定义赋值真除法的行为:/= |
| __ifloordiv__(self, other) | 定义赋值整数除法的行为://= |
| __imod__(self, other) | 定义赋值取模算法的行为:%= |
| __ipow__(self, other[, modulo]) | 定义赋值幂运算的行为:**= |
| __ilshift__(self, other) | 定义赋值按位左移位的行为:<<= |
| __irshift__(self, other) | 定义赋值按位右移位的行为:>>= |
| __iand__(self, other) | 定义赋值按位与操作的行为:&= |
| __ixor__(self, other) | 定义赋值按位异或操作的行为:^= |
| __ior__(self, other) | 定义赋值按位或操作的行为:|= |
| __complex__(self) | 定义当被 complex() 调用时的行为(需要返回恰当的值) |
| __int__(self) | 定义当被 int() 调用时的行为(需要返回恰当的值) |
| __float__(self) | 定义当被 float() 调用时的行为(需要返回恰当的值) |
Python 部分魔法方法
最新推荐文章于 2024-11-18 17:31:42 发布
本文深入解析了Python中特殊方法的功能与使用,包括__new__、__init__、__del__等对象生命周期方法,以及算术操作符如+、-、*、/的定制方法,帮助读者理解如何通过这些方法增强类的特性。
1330

被折叠的 条评论
为什么被折叠?



