python魔法方法之构造和析构

python的类实例化的时候会默认执行该类的构造方法_init_

1 class Rectangle:
2     def __init__(self,x,y):
3         self.x=x
4         self.y=y
5     def getArea(self):
6         return self.x * self.y
7 r = Rectangle(5,10)
8 print(r.getArea())

python中一个类被创建时最先执行的方法是new方法,当需要修改某些不可变类型的对象时需要重写他的new方法

1 #重写int类的new方法使得到的数为正数
2 class A(int):
3     def __new__(cls, value):
4         return super(A, cls).__new__(cls, abs(value))
5 a= A(-5)
6 print(a)
7 
8 5

python中有垃圾回收机制,Python中所有的变量其实都是对内存对象的引用。只有当一个内存对象的引用计数降为0,即没有被变量引用时,解释器的垃圾回收机制才会回收这块内存。只有当内存被真正回收时,__del__方法才会被调用。

 1 class B:
 2     def __init__(self):
 3         print('init')
 4     def __del__(self):
 5         class_name = self.__class__.__name__
 6         print (class_name,"destroy")
 7         
 8 b1= B()
 9 init
10 b2= b1
11 del b2
12 del b1
13 B destroy
原文地址:https://www.cnblogs.com/ymzh/p/8412816.html