成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

您的位置:首頁技術文章
文章詳情頁

python新式類和經典類的區別實例分析

瀏覽:74日期:2022-08-01 15:55:17

本文實例講述了python新式類和經典類的區別。分享給大家供大家參考,具體如下:

新式類就是 class person(object): 這種形式的, 從py2.2 開始出現的

新式類添加了:

__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.

新式類的出現, 除了添加了大量方法以外, 還改變了經典類中一個多繼承的bug, 因為其采用了廣度優先的算法

Python 2.x中默認都是經典類,只有顯式繼承了object才是新式類python 3.x中默認都是新式類,經典類被移除,不必顯式的繼承object

粘貼一段官網上的作者解釋

python新式類和經典類的區別實例分析

是說經典類中如果都有save方法, C中重寫了save() 方法, 那么尋找順序是 D->B->A, 永遠找不到C.save()

代碼演示:

#!/usr/bin/env python3#coding:utf-8’’’ 新式類和經典類的區別, 多繼承代碼演示’’’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()

結果顯示

this is Dsave method from C

注意: 在python3 以后的版本中, 默認使用了新式類, 是不會成功的

另外: 經典類中所有的特性都是可讀可寫的, 新式類中的特性只讀的, 想要修改需要添加 @Texing.setter

更多關于Python相關內容感興趣的讀者可查看本站專題:《Python面向對象程序設計入門與進階教程》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python編碼操作技巧總結》及《Python入門與進階經典教程》

希望本文所述對大家Python程序設計有所幫助。

標簽: Python 編程
相關文章: