继承¶

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

  1. class ClassName(ParentClass):
  2. """class docstring"""
  3. def method(self):
  4. return
  • class 关键词在最前面
  • ClassName 通常采用 CamelCase 记法
  • 括号中的 ParentClass 用来表示继承关系
  • 冒号不能缺少
  • """""" 中的内容表示 docstring,可以省略
  • 方法定义与函数定义十分类似,不过多了一个 self 参数表示这个对象本身
  • class 中的方法要进行缩进
    在里面有一个 ParentClass 项,用来进行继承,被继承的类是父类,定义的这个类是子类。对于子类来说,继承意味着它可以使用所有父类的方法和属性,同时还可以定义自己特殊的方法和属性。

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

In [1]:

  1. class Leaf(object):
  2. def __init__(self, color="green"):
  3. self.color = color
  4. def fall(self):
  5. print "Splat!"

测试:

In [2]:

  1. leaf = Leaf()
  2.  
  3. print leaf.color
  1. green

In [3]:

  1. leaf.fall()
  1. Splat!

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

In [4]:

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

继承父类的所有方法:

In [5]:

  1. mleaf = MapleLeaf()
  2.  
  3. print mleaf.color
  1. green

In [6]:

  1. mleaf.fall()
  1. Splat!

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

In [7]:

  1. mleaf.change_color()
  2.  
  3. print mleaf.color
  1. red

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

In [8]:

  1. class MapleLeaf(Leaf):
  2. def change_color(self):
  3. if self.color == "green":
  4. self.color = "red"
  5. def fall(self):
  6. self.change_color()
  7. print "Plunk!"

In [9]:

  1. mleaf = MapleLeaf()
  2.  
  3. print mleaf.color
  4. mleaf.fall()
  5. print mleaf.color
  1. green
  2. Plunk!
  3. red

原文: https://nbviewer.jupyter.org/github/lijin-THU/notes-python/blob/master/08-object-oriented-programming/08.08-inheritance.ipynb