1.类的构造与析构
1.类的构造方法init(self)和new(cls,other)
在类实例化对象的时候首先调用new()方法,cls参数表示类,other表示其他属性
new除cls外剩余的参数原封不动的传递给init()方法
class Num(int):
def __new__(cls,num):
num += 10
print('__new__方法')
return int.__new__(cls,num)
def __init__(self,num):
print('__init__方法 %d' % num )
def printNum(self):
print('other 方法')
a = Num(0)
a.printNum()
------------------------------------------
__new__方法
__init__方法 0
other 方法
2.del()
在 del 对象的时候调用del()方法
class A:
def __del__(self):
print('---------')
a = A()
del a # ---------
2.类对象
class A:
pass
print(type(A)) # <class 'type'>
print(type(int)) # <class 'type'>
print(type(list)) # <class 'type'>
a = int('5') # 类对象
b = int('10') # 类对象
print(a + b) # 类对象进行相加计算为 15
3.算术运算符
1.算术运算
class AddSub(int):
def __add__(self,other):
return int.__add__(self,other)
def __sub__(self,other):
return int.__sub__(self,other)
a = AddSub(10)
b = AddSub(5)
add = a + b # 调用__add__(a,b)a-->self b-->other
sub = a - b # 调用__sub__(a,b)a-->self b-->other
print(add)
print(sub)
2.反运算
同样3 + 5 计算出来的结果不一样,a对象继承int,a + 时,找int的add方法进行计算
数字3没有add方法,b对象有反运算radd方法,执行此方法,方法内进行减法计算得到为2
class Nint(int):
def __radd__(self,other):
return int.__sub__(self,other)
a = Nint(3)
b = Nint(5)
c = a + b # 8
d = 3 + b # 2
print(c)
print(d)
4.属性访问
class A:
def __init__(self,num = 0):
self.num = num
# 属性被访问时
def __getattribute__(self,num):
print('__getattribute__属性被访问时调用')
return super().__getattribute__(num)
# 访问不存在的属性时
def __getattr__(self,num):
print('__getattr__ 属性不存在时访问')
# 属性被设置时
def __setattr__(self,num,value):
print('__setattr__属性被设置时调用')
super().__setattr__(num,value)
# 属性被删除时
def __delattr__(self,num):
print('__delarre__删除属性')
super().__delattr__(num)
a = A()
----------------
__setattr__属性被设置时调用 # 初始化对象时为num赋值为0,访问num时调用
>>> a.num
__getattribute__属性被访问时调用
0
>>> a.num = 10
__setattr__属性被设置时调用
>>> a.num
__getattribute__属性被访问时调用
10
>>> a.x
__getattribute__属性被访问时调用
__getattr__ 属性不存在时访问
>>> a.x = 10
__setattr__属性被设置时调用
>>> a.x
__getattribute__属性被访问时调用
10
例如:计算长方形(设置square属性为正方形)面积
class Rectangle:
def __init__(self,width,height):
self.width = width
self.height = height
print('__init__')
def __setattr__(self,name,value):
if name == 'square':
self.width = value
self.height = value
print('__setattr__--------square')
else:
print('__setattr__')
super().__setattr__(name,value)
def getArea(self):
return self.width * self.height
-----------------------
>>> r = Rectangle(4,5)
__setattr__
__setattr__
__init__
>>> r.square = 8
__setattr__
__setattr__
__setattr__--------square
>>> r.width
8
>>> r.height
8
>>> r.getArea()
64