Python基础入门学习笔记 041 魔法方法:构造和析构

发布时间 2023-08-23 10:59:15作者: 一杯清酒邀明月

 __init__(self[, ...]) 方法是类在实例化成对象的时候首先会调用的一个方法

 1 >>> class Rectangle:
 2     def __init__(self,x,y):
 3         self.x = x
 4         self.y = y
 5     def getPeri(self):
 6         return (self.x + self.y) * 2
 7     def getArea(self):
 8         return self.x * self.y
 9 >>> rect = Rectangle(5,2)
10 >>> rect.getPeri()
11 14
12 >>> rect.getArea()
13 10

注:__init__()方法的返回值一定是None 

其实,__new__()才是在一个对象实例化时候所调用的第一个方法,它的第一个参数是这个类(cla),而其他的参数会直接传递给__init__()方法

__new__(cls[, ...])

1 >>> class CapStr(str):
2     def __new__(cls,string):
3         string = string.upper()
4         return str.__new__(cls,string)
5 
6     
7 >>> a = CapStr('hello world')
8 >>> a
9 'HELLO WORLD

__del__(self)  当对象将要被销毁的时候,这个方法就会被调用。但要注意,并非del x就相当于调用x.__del__(),__del__()方法是当垃圾回收机制回收这个对象的时候才调用的。

 1 >>> class C:
 2     def __init__(self):
 3         print('我是__init__方法,我被调用了...')
 4     def __del__(self):
 5         print('我是__del__方法,我被调用l...')
 6 
 7         
 8 >>> c1 = C()     #创建对象c1
 9 我是__init__方法,我被调用了...
10 >>> c2 = c1
11 >>> c3 = c2
12 >>> del c1
13 >>> del c2
14 >>> del c3   #删除c3时,对象c1才会彻底被删除(即没有标签指向对象c1时,其才会被回收)
15 我是__del__方法,我被调用l...