一.__init__方法 即我们在定义类时并且在类的实例化时必须执行的一种方法,但注意,引用该方法时不能有返回值,init默认返回值是none
>>> class A: def __init__(self,x,y): self.x=x self.y=y def sqrt(self): print(self.x*self.y) >>> a=A(1,2) >>> a.sqrt() 2 >>> class B: def __init__(self): return 123#不能让init有返回值 >>> a=B() Traceback (most recent call last): File "<pyshell#57>", line 1, in <module> a=B() TypeError: __init__() should return None, not 'int'二.__new__方法 返回一个实例化对象,一般并不需要初始化 三.__del__方法 即垃圾回收机制,当没有变量指向某个对象时,这时才会调用该方法删除这个对象
>>> class C: def __init__(self): print('abcd') def __del__(self): print('del') >>> x1=C() abcd#实例化调用init >>> x2=x1 >>> x3=x1#只是变量之间的相互指向,x1,x2,x3都指向一个对象,并没有再次进行实例化 >>> del x1 >>> del x3 >>> del x2#只有当没有任何变量指向该对象时,才会打印del并删除该对象 del四.算术运算符 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]) 定义当被 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) 定义赋值按位或操作的行为:|= 六.一元操作符 pos(self) 定义正号的行为:+x neg(self) 定义负号的行为:-x abs(self) 定义当被 abs() 调用时的行为 invert(self) 定义按位求反的行为:~x 七.容器类型 len(self) 定义当被 len() 调用时的行为(返回容器中元素的个数) getitem(self, key) 定义获取容器中指定元素的行为,相当于 self[key] setitem(self, key, value) 定义设置容器中指定元素的行为,相当于 self[key] = value delitem(self, key) 定义删除容器中指定元素的行为,相当于 del self[key] iter(self) 定义当迭代容器中的元素的行为 reversed(self) 定义当被 reversed() 调用时的行为 contains(self, item) 定义当使用成员测试运算符(in 或 not in)时的行为
