无意中看到了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