前言
本文以Grid类数据结构为例,围绕如何利用Python实现包接口的开发展开介绍。本文面向于对OOP编程有一定基础的朋友,建议您在阅读本文章前参考学习文章 <面向对象编程>,如果您对【接口函数、模块、包、库 】等概念仍模糊,文章 Python数据结构之基础概念讲解(一)已给出了具象化的详细解释。
注:本系列文章参考自书籍 Fundamentals of Python Data Structure ,博客内容中如有错误,还请大家指出🙏
另:grid类实际上是基于一维数组在维度上的变体,建议您在阅读本文章前浏览一下 基础篇(一)Array类数据结构的包接口开发
硬件资源/配置环境: MacBookPro12,1/VS Code
一、Array 类的准备
请确保在您的Python数据结构学习目录下已创建好arrays.py,因为在完成Grid类的设计过程中需要用到Array类实例。👇
"""
File: arrays.py
An array is like a list, but the client can use only [], len, iter and str
To instantiate, use <variable> = Array(<capacity>, <optional fill value>)
The fill value is None by default
"""
class Array(object):
""" Represents an array """
def __init__(self, capacity, fillValue = None):
""" Capacity is the static size of the array.
fillValue is placed at each position """
self._items = list()
for count in range(capacity):
self._items.append(fillValue)
def __len__(self):
""" -> The capacity of the array """
return len(self._items)
def __str__(self):
""" -> The string representation of the array """
return str(self._items)
def __iter__(self):
""" Support traversal with a for loop """
return iter(self._items)
def __getitem__(self, index):
""" Subscript operator for access at index """
return self._items[index]
def __setitem__(self, index, newItem):
""" Subscript operator for replacement at index """
self._items[index] = newItem
使用命令 python <文件名>
,确保该文件在IDE中正常运行👇
二、定义Grid类
完成好设计框架构建之后,在正式写接口函数之前,需要明确对该函数的说明文档包含内容:
- 在创建接口前要使用文档列出每一个方法头,并用一条单个的
pass
或return
语句来结束每一个方法(注:pass
语句不返回任何值的修改器方法,而每个访问器方法都返回一个简单的默认值,例如False、0或None) - 简略的文档字符串应该包括但不限于:
- 调用时在常规条件下期望输出什么
- 异常情况下输出什么,并显示报错信息(异常处理)
- 详细的说明文档应该包括但不限于:
- 方法的参数
- 先验条件(precondition):当该语句为真时,方法正确执行的操作
- 后验条件(postcondition):(假设先验条件为真)方法执行完毕后,什么条件为真
- 说明未满足先验条件而导致的结果(try…except…)
在Python内置的列表方法中,要创建一个二维数组的基本思想就是,在一维数组的 0~len(one[MAXSIZE])
索引位置下嵌套创建另一个一维数组 other[MAXSIZE]
;借鉴此思路,以准备好的Array类为基础,初始化创建一个Grid类
"""
File: grid.py
"""
from arrays import Array
class Grid(object):
"""Represents a two-dimensional array."""
def __init__(self, rows, columns, fillValue = None):
self.data = Array(rows)
for row in range(rows):
self.data[row] = Array(columns, fillValue)
接着对照Array类提供的基本操作,我们可以在Grid类中声明以下方法:
- 获取该二维数组的行列长度
- 根据索引位置查找数据项
- 以字符串的形式输出
"""
File: grid.py
"""
from arrays import Array
class Grid(object):
"""Represents a two-dimensional array."""
def __init__(self, rows, columns, fillValue = None):
self.data = Array(rows)
for row in range(rows):
self.data[row] = Array(columns, fillValue)
def getHeight(self):
"""Returns the number of rows."""
return len(self.data)
def getWidth(self):
"Returns the number of columns."""
return len(self.data[0])
def __getitem__(self, index):
"""Supports two-dimensional indexing with [][]."""
return self.data[index]
def __str__(self):
"""Returns a string representation of the grid."""
result = ""
for row in range(self.getHeight()):
for col in range(self.getWidth()):
result += str(self.data[row][col]) + " "
result += "\n"
return result
def main():
g = Grid(10, 10, 1)
print(g)
if __name__ == "__main__":
main()
输出为:
三、Matrix对象的创建
基于二维数组,实现矩阵的算术运算。
"""
File: matrix.py
Defines a matrix class to support simple matrix arithmetic.
"""
from grid import Grid
class Matrix(Grid):
"""Represents a matrix."""
def __init__(self, rows, columns, fillValue = 0):
Grid.__init__(self, rows, columns, fillValue)
def __add__(self, other):
"""Returns the sum of self and other."""
sum = Matrix(self.getHeight(), self.getWidth())
for row in range(self.getHeight()):
for col in range(self.getWidth()):
sum[row][col] = self[row][col] + other[row][col]
return sum
def __sub__(self, other):
"""Returns the difference of self and other."""
return Matrix(self.getHeight(), self.getWidth())
def __mul__(self, other):
"""Returns the product of self and other."""
return Matrix(self.getHeight(), self.getWidth())
def main():
m1 = Matrix(3, 3, 2)
print(m1)
m2 = Matrix(3, 3, 4)
print(m2)
print(m1 + m2)
print(m1.__add__(m2))
if __name__ == "__main__":
main()
输出为: