数据抽象( Data Abstraction)
The general technique of isolating the parts of a program that deal with how data are represented from the parts that deal with how data are manipulated is a powerful design methodology called data abstraction。
数据抽象是一种把项目中展示数据的部分与项目中操控数据的部分隔离开来的强大设计方法。也就是不关心如何运作
例如进行有理数的运算时(如1/2 + 2/3),最高层是计算真值的函数add_rational, 第二层是代表分子与分母的操作符,最底层是储存数据的数组[1,2],[2,3]。在求值过程中,上面的层可以调用下面的层的函数,而下面的层不能调用上面的层,否则会产生越界。
例如计算x的幂:
- 正确示例:
# 应该调用第一层mul_rational实现
>>> def square_rational(x):
return mul_rational(x, x)
- 一次抽象越界示例:
"""
rational
x = [1 , 3]
rational(1 * 1, 3 * 3) return [1, 9]
"""
>>> def square_rational_violating_once(x):
return rational(numer(x) * numer(x), denom(x) * denom(x))
- 二次抽象越界示例:
"""
x = [1,3] [1,9]
"""
>>> def square_rational_violating_twice(x):
return [x[0] * x[0], x[1] * x[1]]
All of these implementations of square_rational have the correct behavior, but only the first is robust to future changes. The square_rational function would not require updating even if we altered the representation of rational numbers. By contrast, square_rational_violating_once would need to be changed whenever the selector or constructor signatures changed, and square_rational_violating_twice would require updating whenever the implementation of rational numbers changed.
尽管三种示例结果都是的,但是第一种在遇到变化时,稳定性更强。