构造与析构:
魔法方法被双下划线__包围
__init__(self[,........]):返回值是None,不能有其他返回值
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()
rect.getArea()
__new__(cls[,........]):实例化对象的第一个方法,第一个参数时类,而不是self
class CapStr(str):
def __new__(cls,string):
string=string.upper()
return str.__new__(cls,string)
a=CapString('abc')
__del__(self):析构方法,对象销毁时调用
class C:
def __init__(self):
print('init方法被调用')
def __del__(self):
print('del方法被调用')
c1=C() :实例化
c2=c1 增加变量指向出
c3=c2
del c3
del c2
del c1 :只有在这一步才会调用__del__方法。
这段代码要好好体会
工厂函数:
类型与类一样,可以用type函数查看
a=int('123') :调用类实例化方法
b=int('456')
a+b :对象可以运算
python可以对以下魔法方法进行重定义:
|
__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) |
定义按位或操作的行为:| |
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
观察一下程序:有错误么?
发现出错,发生无限递归。想一想,为什么?
该怎么改?
原因:通过int,把self 、other转为int,而不是Try_int,就不会发生自己调用自己了,避免了无限递归。
反运算:
观察上例:
a+b 正常,因为a实例变量自动继承了int的加法定义
1+b 也正常,因为1是常量,没有继承int类型,所以此时触发b对象的反运算方法__radd__(),其实是在做减法
再举个例子:
说明:调用时self引用的是a,other是3 哈哈哈,意外吧
重写反运算,注意self的顺序