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

继承

一个类定义的基本形式如下:

class ClassName(ParentClass):
    """class docstring"""
    def method(self):
        return
  • class 关键词在最前面
  • ClassName 通常采用 CamelCase 记法
  • 括号中的 ParentClass 用来表示继承关系
  • 冒号不能缺少
  • """""" 中的内容表示 docstring,可以省略
  • 方法定义与函数定义十分类似,不过多了一个 self 参数表示这个对象本身
  • class 中的方法要进行缩进

在里面有一个 ParentClass 项,用来进行继承,被继承的类是父类,定义的这个类是子类。
对于子类来说,继承意味着它可以使用所有父类的方法和属性,同时还可以定义自己特殊的方法和属性。

假设我们有这样一个父类:

class Leaf(object):
    def __init__(self, color="green"):
        self.color = color
    def fall(self):
        print "Splat!"

测试:

leaf = Leaf()

print leaf.color
green
leaf.fall()
Splat!

现在定义一个子类,继承自 Leaf

class MapleLeaf(Leaf):
    def change_color(self):
        if self.color == "green":
            self.color = "red"

继承父类的所有方法:

mleaf = MapleLeaf()

print mleaf.color
green
mleaf.fall()
Splat!

但是有自己独有的方法,父类中没有:

mleaf.change_color()

print mleaf.color
red

如果想对父类的方法进行修改,只需要在子类中重定义这个类即可:

class MapleLeaf(Leaf):
    def change_color(self):
        if self.color == "green":
            self.color = "red"
    def fall(self):
        self.change_color()
        print "Plunk!"
mleaf = MapleLeaf()

print mleaf.color
mleaf.fall()
print mleaf.color
green
Plunk!
red
谨此笔记,记录过往。凭君阅览,如能收益,莫大奢望。
暂无评论

发送评论 编辑评论


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