Python笔记(九)
目录
魔法方法
魔法方法总是被双下划线包围,例如:__init__
魔法方法是面向对象的Python的一切
魔法方法的魔力,体现在它们总能在适当的时候被自动调用
构造与析构
__init__(self[,……])
Python的构造方法,具有初始化的作用,当该类被实例化的时候就会执行该函数,我们就可以把要先初始化的属性放到这个函数里面
例子:求一个矩形的周长和面积,代码如下:
>>> class Rectangle:
def __init__(self,x,y):
self.x = x
self.y = y
def getPeri(self):
return (self.x + self.y) * 2
def getArea(self):
return self.x * self.y
>>> rect = Rectangle(3,4)
>>> rect.getPeri()
14
>>> rect.getArea()
12
如图:
注:init方法返回None,不能有其他返回。
__new__(cls[,…])
__init__与__new__这两个魔法方法组成了Python类对象的构造器,在Python类实例化时,其实最先调用的不是__init__而是__new__。__new__是负责实例化对象的,而__init__是初始化操作。
__new__这个方法极少被重写,但是如果一个类,继承于一个不可改变类型,那就不能在init方法中对它自身进行修改,因为自身不可改变,那么就可以在new中进行替换。
例子:修改字符串全部为大写,代码如下
>>> class CapStr(str):
def __new__(cls,string):
string = string.upper()
return str.__new__(cls,string)
>>> a = CapStr('I love you')
>>> a
'I LOVE YOU'
如图:
__del__(self)
__del__是析构器,当Python对象的所有引用都不存在了(被del了),就会自动触发__del__执行。也就是说,当对象需要被销毁 ,他就会自动被调用。
垃圾回收机制
例子:
>>> class C:
def __init__(self):
print('我是init方法')
def __del__(self):
print('我是del方法')
>>> c1 = C()
我是init方法
>>> c2 = c1
>>> c3 = c2
>>> del c3
>>> del c2
>>> del c1
我是del方法
如图:
注:只有被它的引用都被del后才会在启动垃圾回收机制,执行del方法
算术运算
__add__(self,other)
定义加法的行为+
__sub__(self,other)
定义减法的行为-
看个例子:
>>> class New_int(int):
def __add__(self,other):
return int.__sub__(self,other)
def __sub__(self,other):
return int.__add__(self,other)
>>> a = New_int(3)
>>> b = New_int(5)
>>> a + b
-2
注:看到+,调用__add__方法
如图:
但是下述代码是不可以的:
>>> class Try_int(int):
def __add__(self,other):
return self +other
def __sub__(self,other):
return self + other
>>> a = Try_int(3)
>>> b = Try_int(5)
>>> a + b
Traceback (most recent call last):
File "<pyshell#72>", line 1, in <module>
a + b
File "<pyshell#69>", line 3, in __add__
return self +other
File "<pyshell#69>", line 3, in __add__
return self +other
File "<pyshell#69>", line 3, in __add__
return self +other
[Previous line repeated 991 more times]
RecursionError: maximum recursion depth exceeded
会出现无限递归,抛出异常RecursionError: maximum recursion depth exceeded
如图:
其他算数运算
__mul__(self,other)
定义乘法的行为*
__truediv__(self,other)
定义真除法行为/
__floordiv__(self,ther)
定义整数除法//
__mod__(self,other)
定义取模算法的行为%
__divmod__(self,other)
定义当被divmod()调用时的行为,divmod(a,b)返回值是一个元组(a//b,a%b)
__pow__(self,other)
定义当被power()调用或**运算时的行为
__lshift__(self,other)
定义按位左位移的行为<<
__rshift__(self,other)
定义按位右位移的行为>>
__and__(self,other)
定义按位与操作的行为&
__xor__(self,other)
定义了按位异或操作的行为^
__or__(self,other)
定义了按位或操作的行为|
在Python中我们还可以:
>>> class int(int):
def __add__(self,other):
return int.__sub__(self,other)
>>> a = int('5') #可以看到其他方法没有变化
>>> a
5
>>> b = int(3)
>>> a + b #但是+被重写了
2
其他方法没有变化,但是+被重写
如图:
反运算符
比上述算术运算符多了一个r
例如:__radd__(self,other)
作用与上述相同,当左操作数不支持相应的操作时被调用。
增量赋值运算
比上述算术运算符多了一个i
例如:__iadd__(self,other)
在+=出现时被调用。
一元操作符
__neg__(self) 定义正号的行为+x
__pos__(self) 定义负号的行为-x
__abs__(self) 定义当被abs()调用时的行为,求绝对值
__invvert__(self) 定义按位求反的行为-x