Files
ailearning/docs/da/113.md
2020-10-19 21:08:55 +08:00

177 lines
2.2 KiB
Markdown
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 多重继承
多重继承,指的是一个类别可以同时从多于一个父类继承行为与特征的功能,`Python` 是支持多重继承的:
In [1]:
```py
class Leaf(object):
def __init__(self, color='green'):
self.color = color
class ColorChangingLeaf(Leaf):
def change(self, new_color='brown'):
self.color = new_color
class DeciduousLeaf(Leaf):
def fall(self):
print "Plunk!"
class MapleLeaf(ColorChangingLeaf, DeciduousLeaf):
pass
```
在上面的例子中, `MapleLeaf` 就使用了多重继承,它可以使用两个父类的方法:
In [2]:
```py
leaf = MapleLeaf()
leaf.change("yellow")
print leaf.color
leaf.fall()
```
```py
yellow
Plunk!
```
如果同时实现了不同的接口,那么,最后使用的方法以继承的顺序为准,放在前面的优先继承:
In [3]:
```py
class Leaf(object):
def __init__(self, color='green'):
self.color = color
class ColorChangingLeaf(Leaf):
def change(self, new_color='brown'):
self.color = new_color
def fall(self):
print "Spalt!"
class DeciduousLeaf(Leaf):
def fall(self):
print "Plunk!"
class MapleLeaf(ColorChangingLeaf, DeciduousLeaf):
pass
```
In [4]:
```py
leaf = MapleLeaf()
leaf.fall()
```
```py
Spalt!
```
In [5]:
```py
class MapleLeaf(DeciduousLeaf, ColorChangingLeaf):
pass
```
In [6]:
```py
leaf = MapleLeaf()
leaf.fall()
```
```py
Plunk!
```
事实上,这个顺序可以通过该类的 `__mro__` 属性或者 `mro()` 方法来查看:
In [7]:
```py
MapleLeaf.__mro__
```
Out[7]:
```py
(__main__.MapleLeaf,
__main__.DeciduousLeaf,
__main__.ColorChangingLeaf,
__main__.Leaf,
object)
```
In [8]:
```py
MapleLeaf.mro()
```
Out[8]:
```py
[__main__.MapleLeaf,
__main__.DeciduousLeaf,
__main__.ColorChangingLeaf,
__main__.Leaf,
object]
```
考虑更复杂的例子:
In [9]:
```py
class A(object):
pass
class B(A):
pass
class C(A):
pass
class C1(C):
pass
class B1(B):
pass
class D(B1, C):
pass
```
调用顺序:
In [10]:
```py
D.mro()
```
Out[10]:
```py
[__main__.D, __main__.B1, __main__.B, __main__.C, __main__.A, object]
```