跳转至

继承

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

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

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

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

In [1]:

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

测试:

In [2]:

leaf = Leaf()

print leaf.color
green

In [3]:

leaf.fall()
Splat!

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

In [4]:

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

继承父类的所有方法:

In [5]:

mleaf = MapleLeaf()

print mleaf.color
green

In [6]:

mleaf.fall()
Splat!

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

In [7]:

mleaf.change_color()

print mleaf.color
red

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

In [8]:

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

In [9]:

mleaf = MapleLeaf()

print mleaf.color
mleaf.fall()
print mleaf.color
green
Plunk!
red

我们一直在努力

apachecn/AiLearning

【布客】中文翻译组