zoukankan      html  css  js  c++  java
  • python中的类继承之super

    无意中看到了python类的继承中super的妙用,结合自己的实践,记录一下:


    总结为一句话:如果要用super,那么父类必须继承自object类(包括初始化函数继承和类函数继承),否则会编译不通过
    代码:
    #!/usr/bin/python
    import sys
    import getopt
    #import math
    #coding=utf8
    class AA:
            def __init__(self,a):
                    print "AA class"
                    self.a=a
                    print "self.a:",self.a
    class BB(AA):
            def __init__(self,b):
                    print "BB class"
                    super(BB,self).__init__(b)
                    self.a=b
                    print "self.a:",self.a
            def aa(self,n):
                    print "n:",n
    if __name__ == "__main__":
            a=AA(10)
            b=BB(11)
            print "b:",b
    错误提示:
     File "aa.py", line 19, in __init__
        super(BB,self).__init__(b)
    TypeError: super() argument 1 must be type, not classobj
    正确代码:
    #!/usr/bin/python
    import sys
    import getopt
    #import math
    #coding=utf8
    class AA(object):
            def __init__(self,a):
                    print "AA class"
                    self.a=a
                    print "self.a:",self.a
            def aa(self,m):
                    print "m:",m
                    for i in range(0,10):
                            print i*2;
    class BB(AA):
            def __init__(self,b):
                    print "BB class"
                    #super(BB,self).__init__(b)
                    self.a=b
                    print "self.a:",self.a
            def aa(self,n):
                    print "n:",n
                    print "BB'aa"
                    super(BB,self).aa(n)
    if __name__ == "__main__":
            a=AA(10)
            b=BB(11)
            b.aa(15)
    结果:
    AA class
    self.a: 10
    BB class
    self.a: 11
    n: 15
    BB'aa
    m: 15
    0
    2
    4
    6
    8
    10
    12
    14
    16
    18
  • 相关阅读:
    POJ2186(有向图缩点)
    POJ3352(连通分量缩点)
    POJ1523(割点所确定的连用分量数目,tarjan算法原理理解)
    POJ3694(求割边)
    POJ3177(无向图变双连通图)
    POJ1144(割点入门题)
    maven(1)-linux环境下安装maven
    linux(10)-linux环境下jdk配置自定义环境变量/etc/profile.d以及卸载自带openjdk
    ant(1)-linux环境下安装ant
    apache(2)-linux环境下apache-httpd编译安装
  • 原文地址:https://www.cnblogs.com/aiwa/p/2719094.html
Copyright © 2011-2022 走看看