zoukankan      html  css  js  c++  java
  • Python中新式类 经典类的区别(即类是否继承object)

    首先什么是新式类 经典类呢:

    #新式类是指继承object的类
    class A(obect):
          ...........
    #经典类是指没有继承object的类
    class A:
         ...........
    

    Python中推荐大家使用新式类 1.新的肯定好哈,已经兼容经典类 

                  2.修复了经典类中多继承出现的bug

    下面我们着重说一下多继承的bug 如图:

    BC 为A的子类, D为BC的子类 ,A中有save方法,C对其进行了重写

    在经典类中 调用D的save方法 搜索按深度优先 路径B-A-C, 执行的为A中save 显然不合理
    在新式类的 调用D的save方法 搜索按广度优先 路径B-C-A, 执行的为C中save

    对深度优先,广度优先 有不解的点这里

    #经典类
    class A:
        def __init__(self):
            print 'this is A'
    
        def save(self):
            print 'come from A'
    
    class B(A):
        def __init__(self):
            print 'this is B'
    
    class C(A):
        def __init__(self):
            print 'this is C'
        def save(self):
            print 'come from C'
    
    class D(B,C):
        def __init__(self):
            print 'this is D'
    
    d1=D()
    d1.save()  #结果为'come from A
    
    #新式类
    class A(object):
        def __init__(self):
            print 'this is A'
    
        def save(self):
            print 'come from A'
    
    class B(A):
        def __init__(self):
            print 'this is B'
    
    class C(A):
        def __init__(self):
            print 'this is C'
        def save(self):
            print 'come from C'
    
    class D(B,C):
        def __init__(self):
            print 'this is D'
    
    d1=D()
    d1.save()   #结果为'come from C'
    

      

      

      

  • 相关阅读:
    事件回顾
    把时间花在经典上
    事件回顾
    硬件毛刺
    事件回顾
    cache支持三种pre-fetch方式:normal/pre-fetch1/pre-fetch2-way1/pre-fetch-way2
    cache支持single/increment/increment4三种方式传输
    计算机必读书籍
    那些让我们如此享受的慢性毒药(转载)
    平淡节制
  • 原文地址:https://www.cnblogs.com/hester/p/8135753.html
Copyright © 2011-2022 走看看