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)上的作者解釋
是說經(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 的 __str__ 和 __repr__ 方法對(duì)比2. IntelliJ IDEA設(shè)置默認(rèn)瀏覽器的方法3. Spring security 自定義過濾器實(shí)現(xiàn)Json參數(shù)傳遞并兼容表單參數(shù)(實(shí)例代碼)4. IntelliJ IDEA設(shè)置背景圖片的方法步驟5. docker /var/lib/docker/aufs/mnt 目錄清理方法6. Python TestSuite生成測試報(bào)告過程解析7. 學(xué)python最電腦配置有要求么8. JAMon(Java Application Monitor)備忘記9. Python Scrapy多頁數(shù)據(jù)爬取實(shí)現(xiàn)過程解析10. Python OpenCV去除字母后面的雜線操作
