python新式類和經(jīng)典類的區(qū)別實(shí)例分析
本文實(shí)例講述了python新式類和經(jīng)典類的區(qū)別。分享給大家供大家參考,具體如下:
新式類就是 class person(object): 這種形式的, 從py2.2 開始出現(xiàn)的
新式類添加了:
__name__ is the attribute’s name.__doc__ is the attribute’s docstring.__get__(object) is a method that retrieves the attribute value from object.__set__(object, value) sets the attribute on object to value.__delete__(object, value) deletes the value attribute of object.
新式類的出現(xiàn), 除了添加了大量方法以外, 還改變了經(jīng)典類中一個(gè)多繼承的bug, 因?yàn)槠洳捎昧藦V度優(yōu)先的算法
Python 2.x中默認(rèn)都是經(jīng)典類,只有顯式繼承了object才是新式類python 3.x中默認(rèn)都是新式類,經(jīng)典類被移除,不必顯式的繼承object
粘貼一段官網(wǎng)上的作者解釋
是說(shuō)經(jīng)典類中如果都有save方法, C中重寫了save() 方法, 那么尋找順序是 D->B->A, 永遠(yuǎn)找不到C.save()
代碼演示:
#!/usr/bin/env python3#coding:utf-8’’’ 新式類和經(jīng)典類的區(qū)別, 多繼承代碼演示’’’class A: def __init__(self): print ’this is A’ def save(self): print ’save method from A’class B: def __init__(self): print ’this is B’class C: def __init__(self): print ’this is c’ def save(self): print ’save method from C’class D(B, C): def __init__(self): print ’this is D’d = D()d.save()
結(jié)果顯示
this is Dsave method from C
注意: 在python3 以后的版本中, 默認(rèn)使用了新式類, 是不會(huì)成功的
另外: 經(jīng)典類中所有的特性都是可讀可寫的, 新式類中的特性只讀的, 想要修改需要添加 @Texing.setter
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python面向?qū)ο蟪绦蛟O(shè)計(jì)入門與進(jìn)階教程》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python編碼操作技巧總結(jié)》及《Python入門與進(jìn)階經(jīng)典教程》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
相關(guān)文章:
1. python爬蟲實(shí)戰(zhàn)之制作屬于自己的一個(gè)IP代理模塊2. python實(shí)現(xiàn)讀取類別頻數(shù)數(shù)據(jù)畫水平條形圖案例3. python 利用toapi庫(kù)自動(dòng)生成api4. Android Studio設(shè)置顏色拾色器工具Color Picker教程5. Spring如何使用xml創(chuàng)建bean對(duì)象6. 如何理解PHP核心特性命名空間7. python操作數(shù)據(jù)庫(kù)獲取結(jié)果之fetchone和fetchall的區(qū)別說(shuō)明8. python中PyQuery庫(kù)用法分享9. Spring jdbc具名參數(shù)使用方法詳解10. Springboot設(shè)置默認(rèn)訪問(wèn)路徑方法實(shí)現(xiàn)
