08.08 继承
继承
一个类定义的基本形式如下:
1class ClassName(ParentClass):
2 """class docstring"""
3 def method(self):
4 return
class关键词在最前面ClassName通常采用CamelCase记法- 括号中的
ParentClass用来表示继承关系 - 冒号不能缺少
""""""中的内容表示docstring,可以省略- 方法定义与函数定义十分类似,不过多了一个
self参数表示这个对象本身 class中的方法要进行缩进
在里面有一个 ParentClass 项,用来进行继承,被继承的类是父类,定义的这个类是子类。
对于子类来说,继承意味着它可以使用所有父类的方法和属性,同时还可以定义自己特殊的方法和属性。
假设我们有这样一个父类:
1class Leaf(object):
2 def __init__(self, color="green"):
3 self.color = color
4 def fall(self):
5 print "Splat!"
测试:
1leaf = Leaf()
2
3print leaf.color
green
1leaf.fall()
Splat!
现在定义一个子类,继承自 Leaf:
1class MapleLeaf(Leaf):
2 def change_color(self):
3 if self.color == "green":
4 self.color = "red"
继承父类的所有方法:
1mleaf = MapleLeaf()
2
3print mleaf.color
green
1mleaf.fall()
Splat!
但是有自己独有的方法,父类中没有:
1mleaf.change_color()
2
3print mleaf.color
red
如果想对父类的方法进行修改,只需要在子类中重定义这个类即可:
1class 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!"
1mleaf = MapleLeaf()
2
3print mleaf.color
4mleaf.fall()
5print mleaf.color
green
Plunk!
red