魔方方法之--类的构造(__init__,__new__)和析构(__del__)方法

  1. 构造方法(参见小甲鱼入门教程)

    __ init__()方法:类的初始化方法,初始化类对象时被调用,需要的时候再调用它

  注意点:这个方法的返回值必须None

 class Rectangle():
       def __init__(self,width,height):
           self.width =width
           self.height=height  
View Code

 __ new __ ()方法:实际调调用在__ init __()之前.实例化对象时第一个被调用的方法.在新创建一个对象时调用,一般不会重写它,继承自不可变类型,才显示它的作用

   class CapStr(str):
       def __new__(cls,string):
           string=str.upper(string)
           return str.__new__(cls,string)
   a=CapStr('I will be transfer')
   print(a) #结果 I WILL BE TRANSFER
View Code
  1. 析构方法

  ​ __ del __ ()方法是垃圾回收机制回收对象时调用,对象被删除不一定会调用这个方法.对象地址里面的内容被删为空才会调用这个方法.

  

def __del__(self):
    print('__del__方法被调用了')        
b,c=a,a
c=a
print('del a')
del a
print('del b')
del b
print('del c')
del c #__del__方法被调用了
View Code

 

猜你喜欢

转载自www.cnblogs.com/zhizihuakai66/p/8922628.html