有时候我们会写多个类,那么类与类之间是可以有继承关系的。
例如:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
#!/usr/bin/env python
#-*-coding:utf-8-*-
class father:
def __init__(self):
self.fname =
'fff'
def func(self):
print
'father.func'
class son(father):
def __init__(self):
self.sname =
'sss'
def bar(self):
print
'son.bar'
s1 = son()
s1.bar()
s1.func()
|
输出结果:
1
2
3
|
son.bar
father.func
son.抽烟
|
从上面的例子可以看到
父类中的方法可以被子类继承并调用,调用方式为类.父类中方法名
子类可以继承父类,并重写父类中的方法
例如:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
#!/usr/bin/env python
#-*-coding:utf-8-*-
class father:
def __init__(self):
self.fname =
'fff'
def func(self):
print
'father.func'
def bad(self):
print
'father.抽烟喝酒'
class son(father):
def __init__(self):
self.sname =
'sss'
def bar(self):
print
'son.bar'
def bad(self):
print
'son.抽烟'
s1 = son()
s1.bar()
s1.func()
|
输出结果:
1
2
3
|
son.bar
father.func
son.抽烟
|
子类怎么调用父类的构造函数?
在子类的构造函数中执行父类名.__init__(self)即可
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
#!/usr/bin/env python
#-*-coding:utf-8-*-
class father:
def __init__(self):
self.fname =
'fff'
print
'father.init'
def func(self):
print
'father.func'
def bad(self):
print
'father.抽烟喝酒'
class son(father):
def __init__(self):
self.sname =
'sss'
print
'son.init'
father.__init__(self)
def bar(self):
print
'son.bar'
def bad(self):
print
'son.抽烟'
s1 = son()
s1.bar()
|
输出结果:
1
2
3
|
son.init
father.init
son.bar
|
经典类和新式类
新式类在类名后面有(object)标识。
经典类和新式类的区别:
经典类在类的多重继承时,有一个bug,就是:应该是广度优先,但在多重继承后变成了深度优先。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
#!/usr/bin/env python
#-*-coding:utf-8-*-
class A:
def __init__(self):
print
'This is A'
def save(self):
print
'save 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
'save from C'
class D(B,C):
def __init__(self):
print
'This is D'
c = D()
c.save()
|
输出结果
1
2
|
This is D
save from A
|
从上例可知,D类继承了B和C两个类,并且B优先继承(多重继承时,左边优先继承)
由于B类中没有save方法,而B继承了A,所以D中在继承B时,save方法应该是A类中的save方法。而D又继承了C类,所以最后D类中的最后的sava方法应该是继承C类的,但是上面的结果是D继承了A类。所以这是一个明显的bug。
我们把上例换成新式类在测试下结果:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
#!/usr/bin/env python
#-*-coding:utf-8-*-
class A(object):
def __init__(self):
print
'This is A'
def save(self):
print
'save 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
'save from C'
class D(B,C):
def __init__(self):
print
'This is D'
c = D()
c.save()
|
输出结果:
1
2
|
This is D
save from C
|
总结:新式类修复了经典类的一些bug,并且完全兼容经典类。所以建议使用新式类。
本文转自 曾哥最爱 51CTO博客,原文链接:http://blog.51cto.com/zengestudy/1858476,如需转载请自行联系原作者