python物件導向:小結

來源:互聯網
上載者:User

標籤:PQ   定義類   解決   mysq   set   全域變數   一個   解決方案   學習   

從代碼層級看物件導向

1、在沒有學習類這個概念時,資料與功能是分離的

ef exc1(host,port,db,charset):    conn=connect(host,port,db,charset)    conn.execute(sql)    return xxxdef exc2(host,port,db,charset,proc_name)    conn=connect(host,port,db,charset)    conn.call_proc(sql)    return xxx#每次調用都需要重複傳入一堆參數exc1(‘127.0.0.1‘,3306,‘db1‘,‘utf8‘,‘select * from tb1;‘)exc2(‘127.0.0.1‘,3306,‘db1‘,‘utf8‘,‘預存程序的名字‘)

  

2、能想到的解決方案是,把這些變數都定義成全域變數

HOST=‘127.0.0.1’PORT=3306DB=‘db1’CHARSET=‘utf8’def exc1(host,port,db,charset):    conn=connect(host,port,db,charset)    conn.execute(sql)    return xxxdef exc2(host,port,db,charset,proc_name)    conn=connect(host,port,db,charset)    conn.call_proc(sql)    return xxxexc1(HOST,PORT,DB,CHARSET,‘select * from tb1;‘)exc2(HOST,PORT,DB,CHARSET,‘預存程序的名字‘)

  

3、但是2的解決方案也是有問題的,按照2的思路,我們將會定義一大堆全域變數,這些全域變數並沒有做任何區分,即能夠被所有功能使用,然而事實上只有host,port,db,charset是給exce1,和exc2這兩個功能用的,言外之意:我們必須找出一種能夠將資料與操作資料的方法組合到一起的解決方案,這就是我們說的類了

from pymysql import connectclass mysqlhandler:    def __init__(self, host, port, db, charset="utf-8"):        self.host = host        self.port = port        self.db = db        self.charset = charset        self.conn = connect(self.host, self.port, self.db, self.charset)    def exc1(self, sql):        return self.conn.execute(sql)    def exc2(self, sql):        return self.conn.call_proc(sql)obj = mysqlhandler(‘127.0.0.1‘, 3306, ‘db1‘)obj.exc1(‘select * from tab1‘)obj.exc2(‘預存程序的名字‘)

  總結使用類可以:

將資料與專門操作該資料的功能整合到一起

  

可擴充性高

定義類併產生三個對象

class Chinese:    def __init__(self,name,age,sex):        self.name=name        self.age=age        self.sex=sexp1=Chinese(‘egon‘,18,‘male‘)p2=Chinese(‘alex‘,38,‘female‘)p3=Chinese(‘wpq‘,48,‘female‘)

  

  

如果我們新增一個類屬性,將會立刻反映給所有對象,而對象卻無需修改

class chinese:    country = ‘China‘    def __init__(self, name, age, sex):        self.name = name        self.age = age        self.sex = sex    def tell_info(self):        info = ‘‘‘        國籍:%s        姓名:%s        年齡:%s        性別:%s        ‘‘‘ % (self.country, self.name, self.age, self.sex)        print(info)p1 = chinese(‘egon‘, 18, ‘male‘)p2 = chinese(‘alex‘, 33, ‘female‘)p3 = chinese(‘wpq‘, 50, ‘female‘)print(p1.country)p1.tell_info()

  

python物件導向:小結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.