python 类继承 重写 super MRO

          类继承的好处的就是少写代码。

          重点讲一下,基类中为什么要有super(基类,self).__init__()或patrent.__init__()   

          其实,它们的作用都是一样的,为了MRO

           所谓的MRO是:             

           class Root(object):

def __init__(self): # self.name = name
        # self.age = age
print 'this is Root'
# def t1(self):
    #     print self.name
class B(Root): def __init__(self): # super(B,self).__init__()
Root().__init__() # print self.name
print 'leave B'
class C(Root): def __init__(self): # super(C,self).__init__()
print 'leave C'
class D(B,C): pass this is Root this is Root leave B (<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.Root'>, <type 'object'>) 并不是所有的基类都需要super,只有用到父类的__init__() 关于重写,就是变成子类的方法,原父类的方法不受影响。 
class E(object):
    A = 10
def __init__(self,name):
        self.name = name
        print 'E'
def spam(self):
        # print self.name
print 'spam'
def f1(self):
        print 'patrent.f1',self.name


class F(E):
    def __init__(self):
        super(F,self).__init__('name')
        print 'F'
def f1(self):
    #     print 'F.f1'
F().f1()
        F.A






f = F()
f.spam()
e = E(9999)
e.f1()

reference :
https://laike9m.com/blog/li-jie-python-super,70/
http://ajstar.blog.163.com/blog/static/174234839201011932651799/
http://www.crazyant.net/1303.html

你可能感兴趣的:(类,python)