mirror of
https://github.com/apachecn/ailearning.git
synced 2026-02-10 13:55:05 +08:00
151 lines
2.0 KiB
Markdown
151 lines
2.0 KiB
Markdown
# 继承
|
||
|
||
一个类定义的基本形式如下:
|
||
|
||
```py
|
||
class ClassName(ParentClass):
|
||
"""class docstring"""
|
||
def method(self):
|
||
return
|
||
|
||
```
|
||
|
||
* `class` 关键词在最前面
|
||
* `ClassName` 通常采用 `CamelCase` 记法
|
||
* 括号中的 `ParentClass` 用来表示继承关系
|
||
* 冒号不能缺少
|
||
* `""""""` 中的内容表示 `docstring`,可以省略
|
||
* 方法定义与函数定义十分类似,不过多了一个 `self` 参数表示这个对象本身
|
||
* `class` 中的方法要进行缩进
|
||
|
||
在里面有一个 `ParentClass` 项,用来进行继承,被继承的类是父类,定义的这个类是子类。 对于子类来说,继承意味着它可以使用所有父类的方法和属性,同时还可以定义自己特殊的方法和属性。
|
||
|
||
假设我们有这样一个父类:
|
||
|
||
In [1]:
|
||
|
||
```py
|
||
class Leaf(object):
|
||
def __init__(self, color="green"):
|
||
self.color = color
|
||
def fall(self):
|
||
print "Splat!"
|
||
|
||
```
|
||
|
||
测试:
|
||
|
||
In [2]:
|
||
|
||
```py
|
||
leaf = Leaf()
|
||
|
||
print leaf.color
|
||
|
||
```
|
||
|
||
```py
|
||
green
|
||
|
||
```
|
||
|
||
In [3]:
|
||
|
||
```py
|
||
leaf.fall()
|
||
|
||
```
|
||
|
||
```py
|
||
Splat!
|
||
|
||
```
|
||
|
||
现在定义一个子类,继承自 `Leaf`:
|
||
|
||
In [4]:
|
||
|
||
```py
|
||
class MapleLeaf(Leaf):
|
||
def change_color(self):
|
||
if self.color == "green":
|
||
self.color = "red"
|
||
|
||
```
|
||
|
||
继承父类的所有方法:
|
||
|
||
In [5]:
|
||
|
||
```py
|
||
mleaf = MapleLeaf()
|
||
|
||
print mleaf.color
|
||
|
||
```
|
||
|
||
```py
|
||
green
|
||
|
||
```
|
||
|
||
In [6]:
|
||
|
||
```py
|
||
mleaf.fall()
|
||
|
||
```
|
||
|
||
```py
|
||
Splat!
|
||
|
||
```
|
||
|
||
但是有自己独有的方法,父类中没有:
|
||
|
||
In [7]:
|
||
|
||
```py
|
||
mleaf.change_color()
|
||
|
||
print mleaf.color
|
||
|
||
```
|
||
|
||
```py
|
||
red
|
||
|
||
```
|
||
|
||
如果想对父类的方法进行修改,只需要在子类中重定义这个类即可:
|
||
|
||
In [8]:
|
||
|
||
```py
|
||
class MapleLeaf(Leaf):
|
||
def change_color(self):
|
||
if self.color == "green":
|
||
self.color = "red"
|
||
def fall(self):
|
||
self.change_color()
|
||
print "Plunk!"
|
||
|
||
```
|
||
|
||
In [9]:
|
||
|
||
```py
|
||
mleaf = MapleLeaf()
|
||
|
||
print mleaf.color
|
||
mleaf.fall()
|
||
print mleaf.color
|
||
|
||
```
|
||
|
||
```py
|
||
green
|
||
Plunk!
|
||
red
|
||
|
||
``` |