天天看點

Python學習:構造函數與析構函數

1.構造函數:

​__init__(self)​

​, 這個方法就是構造函數,在執行個體化的時候自動調用。

所有如果這個函數内有列印的方法,當執行個體出來的時候會列印裡面的資訊。

​ __init__​

​​方法的第一個參數永遠都是self,表示建立執行個體本身,在​

​__init__​

​方法内部,可以把各種屬性綁定到self,因為self指向建立的執行個體本身。

有了​

​__init__​

​​方法,在建立執行個體的時候,就不能傳入空的參數了,必須傳入與​

​__init__​

​方法比對的參數,但self不需要傳,Python解釋器自己會把執行個體變量傳進去。

def __init__():
        pass      
lass Baby:
    def __init__(self,name):#構造函數
        self.name = name
    def cry(self):
        self.action = '哭了'
        print(self.action)
feng = Baby('小紅')
print(feng.name)#執行個體化時構造函數自動執行,
print(feng.action)#cry方法未被執行,直接調用feng.action會報錯,object has no attribute對象沒有該屬性      

由于cry方法未被執行,直接調用feng.action會報錯,object has no attribute對象沒有該屬性。解決方法有:

(1)在執行個體化對象後,先調用cry這個方法,在去列印feng.action屬性

class Baby:
    def __init__(self,name):#構造函數
        self.name = name
    def cry(self):
        self.action = '哭了'
        print(self.action)
feng = Baby('小紅')
feng.cry()#先調用cry這個方法
print(feng.action)      

(2)将cry這個方法放在構造函數裡,這樣執行個體化的時候函數會被執行,feng.action屬性就生成了

class Baby:
    def __init__(self,name):#構造函數
        self.name = name
        self.cry()#将cry這個方法放在構造函數裡
    def cry(self):
        self.action = '哭了'
        print(self.action)
feng = Baby('小紅')
print(feng.action)      

2.析構函數:

​__del__(self)​

​, 這個方法就是析構函數,是在執行個體被銷毀時自動調用的。

def __del__():
        pass      
import pymysql
class MySQL(object):
    def __init__(self,host,user,passwd,db,port=3306,charset='utf8'):#構造函數,類執行個體化的時候執行
        try:
            self.conn = pymysql.connect(
                host = host,user=user,passwd=passwd,db=db,port=port,charset=charset,
                autocommit=True  # 自動送出,執行insert,update語句時,可以自動送出
            )
        except Exception as e:
            print('資料庫連接配接失敗,%s'%e)
        else:
            self.cur = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
    def __del__(self):#析構函數,執行個體被銷毀的時候執行
        self.cur.close()
        self.conn.close()
        print('資料庫連接配接關閉')
    def ex_sql(self,sql):
        try:
            self.cur.execute(sql)
        except Exception as e:
            print('sql語句錯誤,%s'%sql)
        else:
            self.res = self.cur.fetchall()
            return self.res #有沒有傳回值都可以
my = MySQL('127.0.0.1', 'root', '123456', 'data')
my.ex_sql('select * from stu')
print(my.res)#可以用執行個體屬性取值
# print(my.ex_sql('select * from stu'))#也可以用執行個體方法的傳回值
print('我是最後一行代碼')#執行完最後一行代碼,資料庫連接配接關閉