031、多重继承
本文最后更新于 68 天前,其中的信息可能已经过时,如有错误请发送邮件到wuxianglongblog@163.com

多重继承

多重继承指的是一个类可以同时从多个父类继承行为与特征的功能。Python 支持多重继承的。

例如,可以将之前的Leaf类进行抽象,树叶Leaf类,父类:

class Leaf(object):
    def __init__(self, color='green'):
        self.color = color

ColorChangingLeaf类,颜色可变的树叶,继承Leaf类:

class ColorChangingLeaf(Leaf):
    def change(self, new_color='brown'):
        self.color = new_color

DeciduousLeaf类,落叶类植物的树叶,继承Leaf类:

class DeciduousLeaf(Leaf):
    def fall(self):
        print("A leaf is falling!")

MapleLeaf类,枫叶,枫叶颜色可变,同时枫树是落叶类植物,可以让它同时继承ColorChangingLeaf类和DeciduousLeaf类。

class MapleLeaf(ColorChangingLeaf, DeciduousLeaf):
    pass

多重继承在定义时,只需要用逗号将多个父类隔开。MapleLeaf类只是简单的继承了两个类型。MapleLeaf类的对象可以使用两个父类的方法:

mleaf = MapleLeaf()

例如,从Leaf类继承而来的属性:

mleaf.color
'green'

从ColorChangingLeaf类继承而来的方法:

mleaf.change("red")
mleaf.color
'red'

从DeciduousLeaf类继承而来方法:

mleaf.fall()
A leaf is falling!

继承顺序

有时候多个父类可能会发生冲突。例如,可以在ColorChangingLeaf的定义中增加一个.fall()方法:

class ColorChangingLeaf(Leaf):
    def change(self, new_color='brown'):
        self.color = new_color

    def fall(self):
        print("I am falling!!!!")

在两个父类的.fall()方法不同时,Python会优先使用定义在前的父类的方法。

当ColorChangingLeaf类在前时,使用的是ColorChangingLeaf类的方法:

class MapleLeaf(ColorChangingLeaf, DeciduousLeaf):
    pass
mleaf = MapleLeaf()
mleaf.fall()
I am falling!!!!

反过来定义时,使用的是DeciduousLeaf类的方法:

class MapleLeaf(DeciduousLeaf, ColorChangingLeaf):
    pass
mleaf = MapleLeaf()
mleaf.fall()
A leaf is falling!

继承的顺序可以通过该类的.__mro__属性或mro()方法来查看:

MapleLeaf.__mro__
(__main__.MapleLeaf,
 __main__.DeciduousLeaf,
 __main__.ColorChangingLeaf,
 __main__.Leaf,
 object)
MapleLeaf.mro()
[__main__.MapleLeaf,
 __main__.DeciduousLeaf,
 __main__.ColorChangingLeaf,
 __main__.Leaf,
 object]
谨此笔记,记录过往。凭君阅览,如能收益,莫大奢望。
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇