|
1 | 1 | \chapter{类和函数} |
| 2 | +\label{ 时间} |
| 3 | + |
| 4 | + |
| 5 | +\section{时间} |
| 6 | + |
| 7 | +作为用户定义类型的另一个例子,我们将定义一个{\tt Time}类,记录当前时间,类的定义如下: |
| 8 | + |
| 9 | +\index{用户定义类型} |
| 10 | +\index{类型!用户定义} |
| 11 | +\index{Time类} |
| 12 | +\index{类!Time} |
| 13 | + |
| 14 | +\beforeverb |
| 15 | +\begin{verbatim} |
| 16 | +class Time(object): |
| 17 | + """represents the time of day. |
| 18 | + attributes: hour, minute, second""" |
| 19 | +\end{verbatim} |
| 20 | +\afterverb |
| 21 | +% |
| 22 | +我们可以创建一个新的{\tt Time}对象,并对时、分和秒进行赋值: |
| 23 | + |
| 24 | +\beforeverb |
| 25 | +\begin{verbatim} |
| 26 | +time = Time() |
| 27 | +time.hour = 11 |
| 28 | +time.minute = 59 |
| 29 | +time.second = 30 |
| 30 | +\end{verbatim} |
| 31 | +\afterverb |
| 32 | +% |
| 33 | +{\tt Time}对象的状态图如下: |
| 34 | + |
| 35 | +\index{状态图} |
| 36 | +\index{图!状态} |
| 37 | +\index{对象图} |
| 38 | +\index{图!对象} |
| 39 | + |
| 40 | +\beforefig |
| 41 | +\centerline{\includegraphics{figs/time.eps}} |
| 42 | +\afterfig |
| 43 | + |
| 44 | +\begin{ex} |
| 45 | +\label{printtime} |
| 46 | +编写函数\verb"print_time",参数为一个时间对象,以{\tt 时:分:秒}的格式打印时间。提示:格式字符串\verb"'%.2d'"使用至少两位打印一个整数,如果需要则在前面添零。 |
| 47 | +\end{ex} |
| 48 | + |
| 49 | +\begin{ex} |
| 50 | +\label{is_after} |
| 51 | + |
| 52 | +\index{布尔函数} |
| 53 | +编写布尔函数\verb"is_after",读取两个时间对象{\tt t1}和{\tt t2},如果{\tt t1}在{\tt t2}之后则返回{\tt True},否则返回{\tt False}。挑战:不使用{\tt if}语句。 |
| 54 | +\end{ex} |
| 55 | + |
| 56 | + |
| 57 | +\section{纯函数} |
| 58 | + |
| 59 | +\index{原型和补丁} |
| 60 | +\index{开发方案!原型和补丁} |
| 61 | +在下面几个章节中,我们将编写两个函数,实现时间相加的功能。它们将展示两种函数:纯函数和修改。同时将给出一个我称为{\bf 原型和补丁}的开发计划,即对于一个复杂的问题,从简单的原型开始,增量地处理其中的复杂问题。 |
| 62 | + |
| 63 | +下面给出\verb"add_time"的一个简单原型: |
| 64 | + |
| 65 | +\beforeverb |
| 66 | +\begin{verbatim} |
| 67 | +def add_time(t1, t2): |
| 68 | + sum = Time() |
| 69 | + sum.hour = t1.hour + t2.hour |
| 70 | + sum.minute = t1.minute + t2.minute |
| 71 | + sum.second = t1.second + t2.second |
| 72 | + return sum |
| 73 | +\end{verbatim} |
| 74 | +\afterverb |
| 75 | +% |
| 76 | +这个函数创建一个新的{\tt Time}对象,初始化其属性并作为引用返回给一个新的对象。这被称为{\bf 纯函数},因为它不改变任何作为参数的对象,除了返回一个值它没有其他作用,类似显示一个值或读取用户输入。 |
| 77 | + |
| 78 | +\index{纯函数} |
| 79 | +\index{函数类型!纯} |
| 80 | + |
| 81 | +我创建了两个时间对象来测试这个函数,{\tt start}包含了一个电影开始的时间,如{\em Monty Python and the Holy Grail},{\tt duration}包含了电影的时间长度,是1小时35分钟。 |
| 82 | + |
| 83 | +\index{Monty Python and the Holy Grail} |
| 84 | + |
| 85 | +\verb"add_time"给出电影结束的时间。 |
| 86 | + |
| 87 | +\beforeverb |
| 88 | +\begin{verbatim} |
| 89 | +>>> start = Time() |
| 90 | +>>> start.hour = 9 |
| 91 | +>>> start.minute = 45 |
| 92 | +>>> start.second = 0 |
| 93 | +
|
| 94 | +>>> duration = Time() |
| 95 | +>>> duration.hour = 1 |
| 96 | +>>> duration.minute = 35 |
| 97 | +>>> duration.second = 0 |
| 98 | +
|
| 99 | +>>> done = add_time(start, duration) |
| 100 | +>>> print_time(done) |
| 101 | +10:80:00 |
| 102 | +\end{verbatim} |
| 103 | +\afterverb |
| 104 | +% |
| 105 | +{\tt 10:80:00}不是你所想要的结果。问题在于这个函数没有处理分钟和秒钟加起来超过60的情况。当这个情况发生时,我们需要将多余的秒钟“进位”到分钟,将多余的分钟“进位”到小时。 |
| 106 | + |
| 107 | +\index{进位,加法} |
| 108 | + |
| 109 | +下面给出一个改进的版本: |
| 110 | + |
| 111 | +\beforeverb |
| 112 | +\begin{verbatim} |
| 113 | +def add_time(t1, t2): |
| 114 | + sum = Time() |
| 115 | + sum.hour = t1.hour + t2.hour |
| 116 | + sum.minute = t1.minute + t2.minute |
| 117 | + sum.second = t1.second + t2.second |
| 118 | +
|
| 119 | + if sum.second >= 60: |
| 120 | + sum.second -= 60 |
| 121 | + sum.minute += 1 |
| 122 | +
|
| 123 | + if sum.minute >= 60: |
| 124 | + sum.minute -= 60 |
| 125 | + sum.hour += 1 |
| 126 | +
|
| 127 | + return sum |
| 128 | +\end{verbatim} |
| 129 | +\afterverb |
| 130 | +% |
| 131 | +虽然这个函数是正确的,但是它开始变得冗长。我们之后会看见一个精简的版本。 |
| 132 | + |
| 133 | + |
| 134 | +\section{修改函数} |
| 135 | +\label{增量} |
| 136 | + |
| 137 | +\index{修改函数} |
| 138 | +\index{函数类型!修改} |
| 139 | + |
| 140 | +有时让函数修改参数对象是很有用的。这中情况下,修改对调用者是可见的。这样工作的函数被称为{\bf 修改函数}。 |
| 141 | + |
| 142 | +\index{increment} |
| 143 | + |
| 144 | +{\tt increment}是将一定秒数加到一个{\tt 时间}对象,可以写成一个修改函数。下面是一个草稿: |
| 145 | + |
| 146 | +\beforeverb |
| 147 | +\begin{verbatim} |
| 148 | +def increment(time, seconds): |
| 149 | + time.second += seconds |
| 150 | +
|
| 151 | + if time.second >= 60: |
| 152 | + time.second -= 60 |
| 153 | + time.minute += 1 |
| 154 | +
|
| 155 | + if time.minute >= 60: |
| 156 | + time.minute -= 60 |
| 157 | + time.hour += 1 |
| 158 | +\end{verbatim} |
| 159 | +\afterverb |
| 160 | +% |
| 161 | +第一行执行基本的操作,后面几行处理我们之前遇到过的特殊情况。 |
| 162 | + |
| 163 | +\index{特殊情况} |
| 164 | + |
| 165 | +这个函数对吗?如果参数{\tt seconds}大于60会怎么样? |
| 166 | + |
| 167 | +在这种情况下,进位一次是不够的,我们需要不断进位直到{\tt time.second}小于60。一个解决方案是使用{\tt while}语句替换{\tt if}语句。这能是函数工作正常,但不是很有效率。 |
| 168 | + |
| 169 | +\begin{ex} |
| 170 | +编写一个正确的{\tt increment},不使用任何循环。 |
| 171 | +\end{ex} |
| 172 | + |
| 173 | +任何修改函数可以做的都可以使用纯函数来实现。事实上有的编程语言只允许纯函数。有些证据证明使用纯函数的程序相比使用修改函数的程序开发更快捷,错误更少。但是修改函数更加方便使用,而函数的编程效率相对较低。 |
| 174 | + |
| 175 | +通常,我推荐你使用纯函数,除非修改函数有明显的优势。这个称为{\bf 函数式编程风格}。 |
| 176 | + |
| 177 | +\index{函数式编程风格} |
| 178 | + |
| 179 | + |
| 180 | +\begin{ex} |
| 181 | +编写纯函数版本的{\tt increment},创建一个新的时间对象并返回,而不是修改参数。 |
| 182 | +\end{ex} |
| 183 | + |
| 184 | + |
| 185 | +\section{原型与计划} |
| 186 | +\label{原型} |
| 187 | + |
| 188 | +\index{原型和补丁} |
| 189 | +\index{开发计划!原型和补丁} |
| 190 | +\index{有计划的开发} |
| 191 | +\index{开发计划!有计划的} |
| 192 | +我在展示的开发计划被称为“原型和补丁”。对于每个函数,我编写实现基本功能的原型并进行测试,并对错误打补丁。 |
| 193 | + |
| 194 | +这个方法会很有效率,尤其是对问题没有一个深入的认识。但是增量的修改会使得代码变得不必要的复杂,因为需要处理不同的特殊情况,同时由于你很难知道是否找到了所有的错误,代码也不可靠。 |
| 195 | + |
| 196 | +另一种是{\bf 有计划的开发},从高层次分析问题将会简化程序的设计。在这个例子中,对问题的分析在于认识到时间对象是3个60进制的数(参考\url{wikipedia.org/wiki/Sexagesimal}。)!{\tt 秒}是“第1列”,{\tt minute}是“第60列”,{\tt 小时}是“第360列”。 |
| 197 | + |
| 198 | +\index{六十进制} |
| 199 | + |
| 200 | +当我们编写\verb"add_time"和{\tt increment},我们完成了基60的加法,这也是为什么我们需要从一列到另一列进位。 |
| 201 | + |
| 202 | +\index{进位,加法} |
| 203 | + |
| 204 | +这个观察给出了解决整个问题的另一个方法,我们可以将时间对象转换为整数,并利用计算机进行整数计算。 |
| 205 | + |
| 206 | +下面的函数将时间转换为整数: |
| 207 | + |
| 208 | +\beforeverb |
| 209 | +\begin{verbatim} |
| 210 | +def time_to_int(time): |
| 211 | + minutes = time.hour * 60 + time.minute |
| 212 | + seconds = minutes * 60 + time.second |
| 213 | + return seconds |
| 214 | +\end{verbatim} |
| 215 | +\afterverb |
| 216 | +% |
| 217 | +下面的函数将整数转换为时间(回忆{\tt divmod}将第一个参数除以第二个参数,并返回商和余数的元组)。 |
| 218 | + |
| 219 | +\index{divmod} |
| 220 | + |
| 221 | +\beforeverb |
| 222 | +\begin{verbatim} |
| 223 | +def int_to_time(seconds): |
| 224 | + time = Time() |
| 225 | + minutes, time.second = divmod(seconds, 60) |
| 226 | + time.hour, time.minute = divmod(minutes, 60) |
| 227 | + return time |
| 228 | +\end{verbatim} |
| 229 | +\afterverb |
| 230 | +% |
| 231 | +你也许需要一些思考,并运行一些测试来确保这些函数工作正常。一个测试方法是对许多{\tt x}值检查\verb"time_to_int(int_to_time(x)) == x"。这是一个强壮型检查的例子。 |
| 232 | + |
| 233 | +\index{强壮型检查} |
| 234 | + |
| 235 | +当你确信它们是正确的,你可以使用它们重写\verb"add_time": |
| 236 | + |
| 237 | +\beforeverb |
| 238 | +\begin{verbatim} |
| 239 | +def add_time(t1, t2): |
| 240 | + seconds = time_to_int(t1) + time_to_int(t2) |
| 241 | + return int_to_time(seconds) |
| 242 | +\end{verbatim} |
| 243 | +\afterverb |
| 244 | +% |
| 245 | +这个版本比原来的简洁,同时也更容易验证。 |
| 246 | + |
| 247 | +\begin{ex} |
| 248 | +使用\verb"time_to_int"和\verb"int_to_time"重写{\tt increment}。 |
| 249 | +\end{ex} |
| 250 | + |
| 251 | +有时候,60进制和10进制的相互转换比处理时间更难。基数转换相对更抽象,我们的直觉更擅长处理时间。 |
| 252 | + |
| 253 | +但是如果我们将时间看成60进制的数,并编写转换函数(\verb"time_to_int"和\verb"int_to_time"),我们使得程序更简短,更适合阅读和调试,以及更可靠。 |
| 254 | + |
| 255 | +同时也方便以后增加新的特性。例如,想象将两个时间相减,得到两者之间的间隔。最直观的方法是实现借位减法。使用转换函数可以更简单,也更容易正确。 |
| 256 | + |
| 257 | +\index{借位减法} |
| 258 | +\index{借位,减法} |
| 259 | +\index{普遍化} |
| 260 | + |
| 261 | +讽刺的是有时候将问题复杂化(或普遍化)实际简化了问题(因为特殊情况变少,同时出错概率减小)。 |
| 262 | + |
| 263 | + |
| 264 | +\section{调试} |
| 265 | +\index{调试} |
| 266 | + |
| 267 | +一个时间对象被称为是良好组织的,如果{\tt 分钟}和{\tt 秒钟}位于0到60(包括0但不包括60),{\tt hours}是正的,{\tt 小时}和{\tt 分钟}是整数,但我们可以允许{\tt 秒钟}有小数部分。 |
| 268 | + |
| 269 | +\index{约束} |
| 270 | + |
| 271 | +类似这些要求被称为{\bf 约束},它们应该始终为真。换言之,如果它们非真,则有些地方就有错误。 |
| 272 | + |
| 273 | +编写程序检查约束可以帮助你检查错误并找出原因。例如,你可以编写函数\verb"valid_time",读取一个时间对象作为参数,如果违反了约束则返回{\tt False}: |
| 274 | + |
| 275 | +\beforeverb |
| 276 | +\begin{verbatim} |
| 277 | +def valid_time(time): |
| 278 | + if time.hours < 0 or time.minutes < 0 or time.seconds < 0: |
| 279 | + return False |
| 280 | + if time.minutes >= 60 or time.seconds >= 60: |
| 281 | + return False |
| 282 | + return True |
| 283 | +\end{verbatim} |
| 284 | +\afterverb |
| 285 | +% |
| 286 | +在每个函数的开头你可以检查参数来保证它们是有效的: |
| 287 | + |
| 288 | +\index{raise语句} |
| 289 | +\index{语句!raise} |
| 290 | + |
| 291 | +\beforeverb |
| 292 | +\begin{verbatim} |
| 293 | +def add_time(t1, t2): |
| 294 | + if not valid_time(t1) or not valid_time(t2): |
| 295 | + raise ValueError, 'invalid Time object in add_time' |
| 296 | + seconds = time_to_int(t1) + time_to_int(t2) |
| 297 | + return int_to_time(seconds) |
| 298 | +\end{verbatim} |
| 299 | +\afterverb |
| 300 | +% |
| 301 | +或者你可以使用{\tt assert}语句,它将检查一个给定的约束,如果检查失败则会发出一个异常错误。 |
| 302 | + |
| 303 | +\index{assert语句} |
| 304 | +\index{语句!assert} |
| 305 | + |
| 306 | +\beforeverb |
| 307 | +\begin{verbatim} |
| 308 | +def add_time(t1, t2): |
| 309 | + assert valid_time(t1) and valid_time(t2) |
| 310 | + seconds = time_to_int(t1) + time_to_int(t2) |
| 311 | + return int_to_time(seconds) |
| 312 | +\end{verbatim} |
| 313 | +\afterverb |
| 314 | +% |
| 315 | +{\tt assert}语句很有用,它们区分普通的条件判断和异常检查。 |
| 316 | + |
| 317 | + |
| 318 | +\section{术语} |
| 319 | + |
| 320 | +\begin{description} |
| 321 | + |
| 322 | +\item[原型和补丁:] 一种开发计划,包括编写程序的草稿、测试、修改发现的错误。 |
| 323 | +\index{原型和补丁} |
| 324 | + |
| 325 | +\item[有计划的开发:] 一种开发计划,包括从高层次对程序进行分析,相对增量开发或原型开发有更多的计划。 |
| 326 | +\index{有计划的开发} |
| 327 | + |
| 328 | +\item[纯函数:] 不修改作为参数的对象的函数。 |
| 329 | +\index{纯函数} |
| 330 | + |
| 331 | +\item[修改函数:] 修改一个或多个作为参数的对象的函数。 |
| 332 | +\index{修改函数} |
| 333 | + |
| 334 | +\item[函数式编程风格:] 一种程序设计模式,将大多数函数设计为纯函数。 |
| 335 | +\index{函数时编程风格} |
| 336 | + |
| 337 | +\item[约束:] 在程序执行时必须始终为真的条件。 |
| 338 | +\index{约束} |
| 339 | + |
| 340 | +\end{description} |
| 341 | + |
| 342 | + |
| 343 | +\section{练习} |
| 344 | + |
| 345 | +\begin{ex} |
| 346 | +编写函数\verb"mul_time",参数为一个时间对象和一个数,返回一个新的时间对象,其值是原时间和数的乘积。 |
| 347 | + |
| 348 | +使用\verb"mul_time"编写一个函数,参数为一个时间对象和一个数值,时间对象表示完成一个比赛所用的时间,数值表示距离,返回一个时间对象,其意义是平均速度(英里每单位时间)。 |
| 349 | + |
| 350 | +\index{跑步速度} |
| 351 | + |
| 352 | +\end{ex} |
| 353 | + |
| 354 | +\begin{ex} |
| 355 | + |
| 356 | +\index{Date类} |
| 357 | +\index{类!Date} |
| 358 | +编写日期对象的类定义,含有属性{\tt 日},{\tt 月}和{\tt 年}。编写函数\verb"increment_date",参数为一个日期对象{\tt date}和一个整数{\tt n},返回值为一个新的日期对象,对应{\tt date}后的{\tt n}天。提示:“2月没有30天...”挑战:你的函数在闰年工作正常吗?参考\url{wikipedia.org/wiki/Leap_year}。 |
| 359 | + |
| 360 | +\end{ex} |
| 361 | + |
| 362 | + |
| 363 | +\begin{ex} |
| 364 | + |
| 365 | +\index{datetime模块} |
| 366 | +\index{模块!datetime} |
| 367 | + |
| 368 | +{\tt datetime}模块提供了类似本章节中的日期和时间对象,{\tt date}和{\tt time},它们提供了丰富的方法和运算符,阅读\url{docs.python.org/lib/datetime-date.html}中的文档。 |
| 369 | + |
| 370 | +\begin{enumerate} |
| 371 | + |
| 372 | +\item 使用{\tt datetime}模块编写程序,读取一个日期,打印这个日期所在的周。 |
| 373 | + |
| 374 | +\index{生日} |
| 375 | + |
| 376 | +\item 编写程序,读如一个生日,打印用户的年龄,以及多少天、小时、分钟和秒钟后是下一个生日。 |
| 377 | +\end{enumerate} |
| 378 | + |
| 379 | +\end{ex} |
| 380 | + |
0 commit comments