Python super

1.当类继承父类时,我们会使用super来进行父类初始化函数的内容。使用super继承父类有两种情况

继承单个父

class test(object):
    def __init__(self):
        self.name="haha"
        self.aa="zxc"

class A(test):
    def __init__(self):
       super(A,self).__init__()
       self.name="test"
        
a=A()
print a.name
print a.aa

继承多个父(每个父类中都必须要有super)

class A(object):
    def __init__(self, arg1):
        print "init func in A, with arg1 '%s'" % arg1
        super(A, self).__init__()
 
class B(object):
    def __init__(self, arg1, arg2):
        print "init func in B, with arg1'%s', arg2 '%s'" % (arg1, arg2)
        super(B, self).__init__(arg1)
 
class C(B, A):
    def __init__(self, arg1, arg2):
        print "init func in C, with arg1'%s', arg2 '%s'" % (arg1, arg2)
        super(C, self).__init__(arg1, arg2)
        print C.__mro__
 
c = C("C's arg1", "C's arg2")

参考链接:http://blog.ptsang.net/constructors_with_different_arguments_in_python_multiinheri_class

posted @ 2017-03-03 15:48  小聪傻大  阅读(163)  评论(0编辑  收藏  举报