03-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

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

是說經典類中如果都有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()

結果顯示  A, 

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

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM