<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                # Chapter 4 Case study: interface design 案例學習:交互設計 This chapter presents a case study that demonstrates a process for designing functions that work together. > 本章會提供一個案例,用于展示如何卻設計一些共同工作的函數。 It introduces the turtle module, which allows you to create images using turtle graphics. The turtle module is included in most Python installations, but if you are running Python using PythonAnywhere, you won’t be able to run the turtle examples (at least you couldn’t when I wrote this). > 本章介紹了小烏龜這個模塊,這允許你用小龜的圖形功能來制作一些圖形。烏龜模塊在大部分的Python中都有安裝,不過如果你在線使用PythnAnywhere,你就無法運行這些烏龜樣例了(至少我寫這本教材的時候還不行)。 > (譯者注:都學到第四章了,你還不本地安裝個Python也太說不過去了吧。) If you have already installed Python on your computer, you should be able to run the examples. Otherwise, now is a good time to install. I have posted instructions at http://tinyurl.com/thinkpython2e. Code examples from this chapter are available from http://thinkpython2.com/code/polygon.py. > 如果你已經安裝了Python在你的電腦上,你就能運行這些例子了。沒安裝的話呢,這就是安裝的好時機了唄。我已經把相關介紹放到網頁上面了,[點擊訪問](http://tinyurl.com/thinkpython2e)。 > 本章代碼樣例可以點擊[此鏈接](http://thinkpython2.com/code/polygon.py)來下載了。 ## 4.1 The turtle module 烏龜模塊 To check whether you have the turtle module, open the Python interpreter and type: > 要檢查你是不是已經安裝了這個烏龜模塊,你要打開Python解釋器來輸入如下內容: ```Python >>> import turtle >>> import turtle >>> bob = turtle.Turtle() >>> bob = turtle.Turtle() ``` When you run this code, it should create a new window with small arrow that represents the turtle. Close the window. > 運行上述例子的時候,應該就能新建一個小窗口,還有個小箭頭象征小烏龜。如果有的話就對了,把窗口關掉吧先。 Create a file named mypolygon.py and type in the following code: > 建立一個叫做mypolygon.py的文件,在里面輸入如下內容: ```Python import turtle bob = turtle.Turtle() print(bob) turtle.mainloop() ``` The turtle module (with a lowercase ’t’) provides a function called Turtle(with an uppercase ’T’) that creates a Turtle object, which we assign to a variable named bob. Printing bob displays something like: > 這個小烏龜模塊(記著是小寫的t)提供了一個叫做Turtle(注意這里是大寫的,大小寫要去分!)的函數,這個函數會創建一個Turtle對象,我們把它賦值給bob這個變量。打印一下bob就能顯示如下內容: ```Bash <turtle.Turtle object at 0xb7bfbf4c> ``` This means that bob refers to an object with type Turtle as defined in module turtle. > 這就意味著bob已經指向了模塊turtle中所定義的Turtle類的一個對象。 mainloop tells the window to wait for the user to do something, although in this case there’s not much for the user to do except close the window. > mainloop這個函數是告訴窗口等用戶來做些事情,當然本次嘗試的情況下用戶也就是關閉窗口而已了。 Once you create a Turtle, you can call a method to move it around the window. A method is similar to a function, but it uses slightly different syntax. For example, to move the turtle forward: > 一旦你創建了一個Trutle,你就可以調用一些方法讓他在窗口中移動。方法跟函數有點相似,但語法的使用稍微不太一樣。比如你可以讓小烏龜往前走: ```Python bob.fd(100) ``` The method, fd, is associated with the turtle object we’re calling bob. Calling a method is like making a request: you are asking bob to move forward. > fd這個方法,是turtle類這個叫做bob的對象所包含的。調用這個方法就像是做出一個請求一樣:你再讓bob向前移動。 The argument of fd is a distance in pixels, so the actual size depends on your display. > fd這個方法的參數是像素數距離,所以實際的大小依賴于你顯示器的情況了。 Other methods you can call on a Turtle are bk to move backward, lt for left turn, and rt right turn. The argument for lt and rt is an angle in degrees. > Turtle對象中還有一些其他方法,比如bk是后退,lt是左轉,rt是右轉。lt和rt用偏轉角度做參數。 Also, each Turtle is holding a pen, which is either down or up; if the pen is down, the Turtle leaves a trail when it moves. The methods pu and pd stand for “pen up” and “pen down”. > 另外,每個Turtle都相當于帶著筆,可以落下或者抬起;如果筆落下了,Turtle移動的時候就會留下軌跡了。抬筆落筆的方法縮寫粉筆嗯是pu和pd。 To draw a right angle, add these lines to the program (after creating bob and before calling mainloop): > 畫一個直角,就要把下面這些線加到程序里面(當然要先創建一個bob并且在此之前運行mainloop): ```Python bob.fd(100) bob.lt(90) bob.fd(100) ``` When you run this program, you should see bob move east and then north, leaving two line segments behind. > 運行這個程序,你就能看到bob先向東再往北,后面就留下了兩根互相垂直的線段了。 Now modify the program to draw a square. Don’t go on until you’ve got it working! > 現在修改一下程序,去畫一個正方形。這個程序運行不好的話就不要繼續后面的章節! ## 4.2 Simple repetition 簡單的重復 Chances are you wrote something like this: > 你估計會寫出如下的內容: ```Python bob.fd(100) bob.lt(90) bob.fd(100) bob.lt(90) bob.fd(100) bob.lt(90) bob.fd(100) ``` We can do the same thing more concisely with a for statement. Add this example to mypolygon.py and run it again: > 上面這個太麻煩了,咱們可以用一個for語句來讓這個過程更簡潔。把下面的代碼添加到mypolygon.py中然后運行一下: ```Python for i in range(4): print('Hello!') ``` You should see something like this: > 你將會看到這樣的輸出: ```Bash Hello! Hello! Hello! Hello! ``` This is the simplest use of the for statement; we will see more later. But that should be enough to let you rewrite your square-drawing program. Don’t go on until you do. > 這就是for語句的最簡單的一種應用;以后我們會看到更多。不過當前這種簡單的足夠你來重構一下你的正方形繪制程序了。不達目的不罷休,不要跳過困難哈,一定要編寫出來這個再進行后面的內容。 Here is a for statement that draws a square: > 這就是一個用for語句來畫正方形的語句: ```Python for i in range(4): bob.fd(100) bob.lt(90) ``` The syntax of a for statement is similar to a function definition. It has a header that ends with a colon and an indented body. The body can contain any number of statements. > for語句的語法跟函數定義有點相似。有一個頭部,頭部的結尾要用冒號,然后還有一個縮進的循環體。循環體可以包含任意多的語句。 A for statement is also called a loop because the flow of execution runs through the body and then loops back to the top. In this case, it runs the body four times. > for語句也被叫做循環,因為運行流程會重復執行循環體。在本節的例子中,循環進行了四次。 This version is actually a little different from the previous square-drawing code because it makes another turn after drawing the last side of the square. The extra turn takes more time, but it simplifies the code if we do the same thing every time through the loop. This version also has the effect of leaving the turtle back in the starting position, facing in the starting direction. > 這次的正方形繪制代碼實際上和之前的少有不同了,因為在畫完了最后一個邊之后,多了一次轉向。多出來的這部分需要消耗額外的時間,但簡化了下次我們來循環進行繪制的過程。這個版本的代碼也有一個額外的效果:讓小烏龜回到起點,朝著初始方向。 ## 4.3 Exercises 練習 The following is a series of exercises using TurtleWorld. They are meant to be fun, but they have a point, too. While you are working on them, think about what the point is. > 下面是一系列使用TurtleWorld的練習。主要就是比較有意思,不過也有一些訓練的作用。你做這些練習的時候,一定要注意考慮這些訓練的作用。 The following sections have solutions to the exercises, so don’t look until you have finished (or at least tried). > 練習后面是有一些樣例的解決方案的,所以你要做完了再往后看,至少你得試試,不會做了看看答案也行哈。 1.Write a function called square that takes a parameter named t, which is a turtle. It should use the turtle to draw a square. > 寫一個函數叫做square(譯者注:就是正方形的意思),有一個名叫t的參數,這個t是一個turtle。用這個turtle來畫一個正方形。 Write a function call that passes bob as an argument to square, and then run the program again. > 寫一個函數調用,把bob作為參數傳遞給square,然后再運行這個程序。 2.Add another parameter, named length, to square. Modify the body so length of the sides is length, and then modify the function call to provide a second argument. Run the program again. Test your program with a range of values for length. > 給這個square函數再加一個參數,叫做length(譯者注:長度)。把函數體修改一下,讓長度length賦值給各個邊的長度,然后修改一下調用函數的代碼,再提供一個這個對應長度的參數。再次運行一下,用一系列不同的長度值來測試一下你的程序。 3.Make a copy of square and change the name to polygon. Add another parameter named n and modify the body so it draws an n-sided regular polygon. Hint: The exterior angles of an n-sided regular polygon are 360/n degrees. > 復制一下square這個函數,把名字改成polygon(譯者注:意思為多邊形)。另外添加一個參數叫做n,然后修改函數體,讓函數實現畫一個正n邊的多邊形。提示:正n多邊形的外角為360/n度。 4.Write a function called circle that takes a turtle, t, and radius, r, as parameters and that draws an approximate circle by calling polygon with an appropriate length and number of sides. Test your function with a range of values of r. > 在寫一個叫做circle(譯者注:圓)的函數,也用一個turtle類的對象t,以及一個半徑r,作為參數,畫一個近似的圓,通過調用polygon函數來近似實現,用適當的邊長和邊數。用不同的半徑值來測試一下你的函數。 Hint: figure out the circumference of the circle and make sure that length * n = circumference. > 提示:算出圓的周長,確保邊長乘以邊數的值(近似)等于圓周長。 5.Make a more general version of circle called arc that takes an additional parameter angle, which determines what fraction of a circle to draw. angle is in units of degrees, so when angle=360, arc should draw a complete circle. > 在circle基礎上做一個叫做arc的函數,在circle的基礎上添加一個angle(譯者注:角度)變量,用這個角度值來確定畫多大的一個圓弧。用度做單位,當angle等于360度的時候,arc函數就應當畫出一個整團了。 ## 4.4 Encapsulation 封裝 The first exercise asks you to put your square-drawing code into a function definition and then call the function, passing the turtle as a parameter. Here is a solution: > 第一個練習讓你把正方形繪制的代碼定義到一個函數里面,然后調用這個函數,傳入一個turtle對象作為參數。下面就是個例子了: ```Python def square(t): for i in range(4): t.fd(100) t.lt(90) square(bob) ``` The innermost statements, fd and lt are indented twice to show that they are inside the for loop, which is inside the function definition. The next line,square(bob), is flush with the left margin, which indicates the end of both the for loop and the function definition. > 在最內部的語句里面,fd和lt縮進了兩次,這個意思是他們是for循環的循環體內部成員,而for循環本身縮進了一次,說明for語句被包含在函數的定義當中。接下來的那行square(bob),緊靠左側,沒有縮進,這說明for循環和函數定義都結束了。 Inside the function, t refers to the same turtle bob, so t.lt(90) has the same effect as bob.lt(90). In that case, why not call the parameter bob? The idea is that t can be any turtle, not just bob, so you could create a second turtle and pass it as an argument to square: > 在函數體內部,t所指代的就是小烏龜bob,因此讓t來左轉九十度的效果完全等同于讓bob來左轉九十度。本文中沒有把形式參數的名字設置成bob,這是為啥呢?是因為用t可以指代任意一個小烏龜,不僅僅是bob,所以你就能再創建另一個小烏龜,把它傳遞給square這個函數作為實際參數: ```Python alice = Turtle() square(alice) ``` Wrapping a piece of code up in a function is called encapsulation. One of the benefits of encapsulation is that it attaches a name to the code, which serves as a kind of documentation. Another advantage is that if you reuse the code, it is more concise to call a function twice than to copy and paste the body! > 用函數的形式把一段代碼包裝起來,叫做封裝。這樣有一個好處,就是給代碼起了個名字,有類似文檔說明的功能,更好理解了。另外一個好處是下次重復使用這段代碼的時候,再次調用函數就可以了,這比復制粘貼函數體可方便多了。 ## 4.5 Generalization 泛化 The next step is to add a length parameter to square. Here is a solution: > 下一步就是給square函數添加一個長度參數了。下面是樣例: ```Python def square(t, length): for i in range(4): t.fd(length) t.lt(90) square(bob, 100) ``` Adding a parameter to a function is called generalization because it makes the function more general: in the previous version, the square is always the same size; in this version it can be any size. > 給函數添加參數,就叫做泛化,因為者可以讓函數的功能更廣泛:在之前的版本中,square這個函數畫出來的正方形總是一個尺寸的;在這個新版本里面,可以自定義邊長了。 The next step is also a generalization. Instead of drawing squares, polygondraws regular polygons with any number of sides. Here is a solution: > 下一步也還是泛化。這次就是不光要畫正方形了,要畫一個多邊形,可以指定邊數的。下面是樣例: ```Python def polygon(t, n, length): angle = 360 / n for i in range(n): t.fd(length) t.lt(angle) polygon(bob, 7, 70) ``` This example draws a 7-sided polygon with side length 70. > 這個例子畫了一個每個邊長度都為70像素的七邊形。 If you are using Python 2, the value of angle might be off because of integer division. A simple solution is to compute angle = 360.0 / n. Because the numerator is a floating-point number, the result is floating point. > 如果你用Python2的話,角度可能因為整除而導致的偏差。簡單的解決方法就是用360.0來除以n而不是用360,這就是用浮點數替代了原來的整形,結果就是一個浮點數了。 When a function has more than a few numeric arguments, it is easy to forget what they are, or what order they should be in. In that case it is often a good idea to include the names of the parameters in the argument list: > 當一個函數有超過一個數據參數的時候,很容易忘掉這些參數都是什么,或者忘掉他們的順序。為了避免這個情況,可以把形式參數的名字包含在一個實際參數列表中: ```Python polygon(bob, n=7, length=70) ``` These are called keyword arguments because they include the parameter names as “keywords” (not to be confused with Python keywords like whileand def). > 這些列表叫做關鍵參數列表,因為他們把形式參數的名字作為關鍵詞包含了進來。(注意區別這里的關鍵詞可不是Python語言的關鍵詞哈!這里就是字面意思,很關鍵的詞。) This syntax makes the program more readable. It is also a reminder about how arguments and parameters work: when you call a function, the arguments are assigned to the parameters. > 這種語法結構讓程序更容易被人讀懂。也能提醒實際參數和形式參數的使用過程:調用一個函數的時候,把實際參數的值賦給了形式參數。 ## 4.6 Interface design 界面設計 The next step is to write circle, which takes a radius, r, as a parameter. Here is a simple solution that uses polygon to draw a 50-sided polygon: > 下一步就是寫circle這個函數了,需要半徑r作為一個參數。下面是一個簡單的樣例,使用polygon函數來畫一個50邊形,來接近一個圓: ```Python import math def circle(t, r): circumference = 2 * math.pi * r n = 50 length = circumference / n polygon(t, n, length) ``` The first line computes the circumference of a circle with radius r using the formula 2 π r. Since we use math.pi, we have to import math. By convention,import statements are usually at the beginning of the script. > 第一行計算了圓的周長,使用2乘以圓周率再乘以半徑r。這個計算用到了圓周率,所以要導入math模塊。通常都要把導入語句放到整個腳本的開頭。 n is the number of line segments in our approximation of a circle, so length is the length of each segment. Thus, polygon draws a 50-sides polygon that approximates a circle with radius r. > n是我們用來逼近一個圓所用的線段數量,所以length就是每一個線段的長度了。polygon畫一個50邊的多邊形,來近似做一個半徑為r的圓。 One limitation of this solution is that n is a constant, which means that for very big circles, the line segments are too long, and for small circles, we waste time drawing very small segments. One solution would be to generalize the function by taking n as a parameter. This would give the user (whoever calls circle) more control, but the interface would be less clean. > 這種方案的一個局限性就是n是常數,就意味著對于一些大尺寸的圓,線段數目就太多了,而對小的圓,又浪費了很多小線段。解決的方法就是進一步擴展函數,讓函數把n也作為一個參數。這就虧讓用戶(調用circle函數的任何人)有更多決定權,可以控制所用的線段數量,當然,界面就不那么簡潔了。 The interface of a function is a summary of how it is used: what are the parameters? What does the function do? And what is the return value? An interface is “clean” if it allows the caller to do what they want without dealing with unnecessary details. > 函數的界面就是關于它如何工作的一個概述:都有什么變量?函數實現什么功能?以及返回值是什么?允許調用者隨意操作而不用處理一些無關緊要的細節,這種函數界面就是簡潔的。 In this example, r belongs in the interface because it specifies the circle to be drawn. n is less appropriate because it pertains to the details of how the circle should be rendered. > 在本節的例子中,r包含于界面內,因為要用它來確定所畫圓的大小。n就不那么合適了,因為它是用來處理如何具體繪制一個圓的。 Rather than clutter up the interface, it is better to choose an appropriate value of n depending on circumference: > 與其讓界面復雜冗余,更好的思路是讓n根據周長來自適應一個合適的值: ```Python def circle(t, r): circumference = 2 * math.pi * r n = int(circumference / 3) + 1 length = circumference / n polygon(t, n, length) ``` Now the number of segments is an integer near circumference/3, so the length of each segment is approximately 3, which is small enough that the circles look good, but big enough to be efficient, and acceptable for any size circle. > 現在線段個數就是周長的三分之一了,因此每段線段的長度近似為3,這個大小可以讓圓看著不錯,也對任意大小的圓都適用了。 ## 4.7 Refactoring 重構 When I wrote circle, I was able to reuse polygon because a many-sided polygon is a good approximation of a circle. But arc is not as cooperative; we can’t use polygon or circle to draw an arc. > 當我寫circle這個函數的時候,我能利用多邊形函數polygon是因為一個足夠多邊的多邊形和圓很接近。但圓弧就不太適合這個思路了;我們不能用多邊形或者圓來畫一個圓弧。 One alternative is to start with a copy of polygon and transform it into arc. The result might look like this: > 一個替代的方法就是把polygon修改一下,轉換成圓弧。結果大概如下所示: ```Python def arc(t, r, angle): arc_length = 2 * math.pi * r * angle / 360 n = int(arc_length / 3) + 1 step_length = arc_length / n step_angle = angle / n for i in range(n): t.fd(step_length) t.lt(step_angle) ``` The second half of this function looks like polygon, but we can’t reuse polygon without changing the interface. We could generalize polygon to take an angle as a third argument, but then polygon would no longer be an appropriate name! Instead, let’s call the more general function polyline: > 這個函數的后半段看著和多邊形那個還挺像的,但必須修改一下界面才能重利用多邊形的代碼。我們在多邊形函數上增加angle(角度)作為第三個參數,但繼續叫多邊形就不太合適了,因為不閉合啊!所以就改名叫它多段線polyline: ```Python def polyline(t, n, length, angle): for i in range(n): t.fd(length) t.lt(angle) ``` Now we can rewrite polygon and arc to use polyline: > 現在就可以用多段線polyline來重寫多邊形polygon和圓弧arc: ```Python def polygon(t, n, length): angle = 360.0 / n polyline(t, n, length, angle) def arc(t, r, angle): arc_length = 2 * math.pi * r * angle / 360 n = int(arc_length / 3) + 1 step_length = arc_length / n step_angle = float(angle) / n polyline(t, n, step_length, step_angle) ``` Finally, we can rewrite circle to use arc: > 最終,咱們就可以用圓弧arc來重寫circle的實現了: ```Python def circle(t, r): arc(t, r, 360) ``` This process—rearranging a program to improve interfaces and facilitate code re-use—is called refactoring. In this case, we noticed that there was similar code in arc and polygon, so we “factored it out” into polyline. > 這個過程中,改進了界面設計,增強了代碼再利用,這就叫做重構。在本節的這個例子中,我們先是注意到圓弧arc和多邊形polygon有相似的代碼,所以我們把他們都用多段線polyline來實現。 If we had planned ahead, we might have written polyline first and avoided refactoring, but often you don’t know enough at the beginning of a project to design all the interfaces. Once you start coding, you understand the problem better. Sometimes refactoring is a sign that you have learned something. > 如果我們事先進行了計劃,估計就會先寫出多段線函數polyline,然后就不用重構了,但大家在開始一個項目之前往往不一定了解的那么清楚。一旦開始編碼了,你就逐漸更理解其中的問題了。有時候重構就意味著你已經學到了新的內容了。 ## 4.8 A development plan 開發計劃 A development plan is a process for writing programs. The process we used in this case study is “encapsulation and generalization”. The steps of this process are: > 開發計劃是寫程序的一系列過程。我們本章所用的就是『封裝-泛化』的模式。這一過程的步驟如下: 1. Start by writing a small program with no function definitions. > 開始寫一個特別小的程序,沒有函數定義。 2. Once you get the program working, identify a coherent piece of it, encapsulate the piece in a function and give it a name. > 一旦有你的程序能用了,確定一下實現功能的這部分有練習的語句,封裝成函數,并命名一下。 3. Generalize the function by adding appropriate parameters. > 通過逐步給這個函數增加參數的方式來泛化。 4. Repeat steps 1–3 until you have a set of working functions. Copy and paste working code to avoid retyping (and re-debugging). > 重復1-3步驟,一直到你有了一系列能工作的函數為止。把函數復制粘貼出來,避免重復輸入或者修改了。 5. Look for opportunities to improve the program by refactoring. For example, if you have similar code in several places, consider factoring it into an appropriately general function. > 看看是不是有通過重構來改進函數的可能。比如,假設你在一些地方看到了相似的代碼,就可以把這部分代碼做成一個函數。 This process has some drawbacks—we will see alternatives later—but it can be useful if you don’t know ahead of time how to divide the program into functions. This approach lets you design as you go along. > 這個模式有一些缺點,我們后續會看到一些替代的方式,但這個模式是很有用的,尤其對耐餓實現不值得怎么去把程序分成多個函數的情況。 ## 4.9 docstring 文檔字符串 A docstring is a string at the beginning of a function that explains the interface (“doc” is short for “documentation”). Here is an example: > 文檔字符串是指:在函數開頭部位,解釋函數的交互界面的字符串,doc是文檔documentation的縮寫。下面是一個例子: ```Python def polyline(t, n, length, angle): """ Draws n line segments with the given length and angle (in degrees) between them. t is a turtle. """ for i in range(n): t.fd(length) t.lt(angle) ``` By convention, all docstrings are triple-quoted strings, also known as multiline strings because the triple quotes allow the string to span more than one line. > 一般情況下,所有文檔字符串都是三重引用字符串,也被叫做多行字符串,因為三重的單引號表示允許這個字符串是多行的。 It is terse, but it contains the essential information someone would need to use this function. It explains concisely what the function does (without getting into the details of how it does it). It explains what effect each parameter has on the behavior of the function and what type each parameter should be (if it is not obvious). > 這些文字很簡潔,但都包含了一些關鍵的信息,這些信息對于函數使用者來說至關重要。這些信息簡要解釋了函數的用途(不會說細節,也不會說如何實現)。文檔解釋了每個參數對函數行為的影響,以及各自的類型(一般在不是顯而易見的情況下就給解釋了)。 Writing this kind of documentation is an important part of interface design. A well-designed interface should be simple to explain; if you have a hard time explaining one of your functions, maybe the interface could be improved. > 寫這種文檔,對交互界面的設計來說,是至關重要的。設計良好的交互界面應該很容易解釋明白;如果你的函數有一個特別不好解釋了,估計這個函數的交互設計還存在需要改進的地方。 ## 4.10 Debugging 調試 An interface is like a contract between a function and a caller. The caller agrees to provide certain parameters and the function agrees to do certain work. > 一個交互界面,就像是函數和調用者的一個中間人。調用者提供特定的參數,函數完成特定的任務。 For example, polyline requires four arguments: t has to be a Turtle; n has to be an integer; length should be a positive number; and angle has to be a number, which is understood to be in degrees. > 例如,polyline這個多段線函數,需要四個實際參數:t必須是一個Turtle小烏龜;n(邊數)必須是一個整形;length(長度)應該是一個正數;angle(角度)必須是一個以度為單位的角度值。 These requirements are called preconditions because they are supposed to be true before the function starts executing. Conversely, conditions at the end of the function are postconditions. Postconditions include the intended effect of the function (like drawing line segments) and any side effects (like moving the Turtle or making other changes). > 這些要求叫做『前置條件』,因為要在函數開始運行之前就要實現才行。相應的在函數的結尾那里的條件叫『后置條件』。后置條件包含函數的預期效果(如畫線段)和其他作用(如移動海龜或進行其他改動)。 Preconditions are the responsibility of the caller. If the caller violates a (properly documented!) precondition and the function doesn’t work correctly, the bug is in the caller, not the function. > 前置條件是準備給函數調用者的。如果調用者違背了(妥當標注的)前置條件,然后函數不能正常工作,這個bug就會反饋在函數調用者上,而不是函數本身。 If the preconditions are satisfied and the postconditions are not, the bug is in the function. If your pre- and postconditions are clear, they can help with debugging. > 如果前置條件得到了滿足,而后置條件未能滿足,這個bug就是函數的了。所以如果你的前后置條件都弄清晰,對調試很有幫助。 ## 4.11 Glossary 術語列表 method: A function that is associated with an object and called using dot notation. > 方法:某個類中一個對象所具有的函數,用點連接來進行調用。 loop: A part of a program that can run repeatedly. > 循環:程序中重復運行的一部分。 encapsulation: The process of transforming a sequence of statements into a function definition. > 封裝:把一系列相關的語句整理定義成一個函數的過程。 generalization: The process of replacing something unnecessarily specific (like a number) with something appropriately general (like a variable or parameter). > 泛化:把一些不必要的內容用更廣泛通用的內容來替換掉的過程,比如把一個數字替換成了一個變量或者參數。 keyword argument: An argument that includes the name of the parameter as a “keyword”. > 關鍵詞參數:一種特殊的實際參數,把形式參數的名字作為關鍵詞包含在內。 interface: A description of how to use a function, including the name and descriptions of the arguments and return value. > 交互界面:對如何使用一個函數的描述,包括了函數名,以及對實際參數和返回值的描述。 refactoring: The process of modifying a working program to improve function interfaces and other qualities of the code. > 重構:對一份能工作的程序進行修改,改進函數交互界面以及提高代碼其他方面質量的過程。 development plan: A process for writing programs. > 開發計劃:寫程序的過程。 docstring: A string that appears at the top of a function definition to document the function’s interface. > 文檔字符串:一個在函數定義的頂部的字符串,講解函數的交互界面。 precondition: A requirement that should be satisfied by the caller before a function starts. > 前置條件:函數開始之前,調用者應當滿足的要求。 postcondition: A requirement that should be satisfied by the function before it ends. > 后置條件:函數結束之前應該滿足的一些要求。 ## 4.12 Exercises 練習 ### Exercise 1 練習1 Download the code in this chapter from [here](http://thinkpython2.com/code/polygon.py). > 點擊下面這個鏈接[下載代碼](http://thinkpython2.com/code/polygon.py)。 1. Draw a stack diagram that shows the state of the program while executing circle(bob, radius). You can do the arithmetic by hand or add print statements to the code. > 畫一個棧圖,表明運行函數circle(bob,radius)時候程序的狀態。你可以手算一下,或者把輸出語句加到代碼上。 2. The version of arc in Section 4.7 is not very accurate because the linear approximation of the circle is always outside the true circle. As a result, the Turtle ends up a few pixels away from the correct destination. My solution shows a way to reduce the effect of this error. Read the code and see if it makes sense to you. If you draw a diagram, you might see how it works. > 4.7小節中的那個版本的arc函數并不太精確,因為對圓進行線性逼近總會超過真實情況。結果就是小烏龜總會距離正確位置偏離一些像素。我的樣例給出了一種降低這種誤差程度的方法。閱讀一下代碼,看你能不能理解。如果你畫一個圖標,也許就能明白代碼是怎么工作的了。 * * * ![Turtle flowers](http://7xnq2o.com1.z0.glb.clouddn.com/ThinkPythonExercise4.2.png) Figure 4.1: Turtle flowers. * * * ### Exercise 2 練習2 Write an appropriately general set of functions that can draw flowers as in Figure 4.1. > 寫一系列的合適的函數組合,畫出圖4.1所示的花圖案。 Solution 樣例: http://thinkpython2.com/code/flower.py, also requires 同時需要: http://thinkpython2.com/code/polygon.py. * * * ![Turtle pies](http://7xnq2o.com1.z0.glb.clouddn.com/ThinkPythonExercise4.3.png) Figure 4.2: Turtle pies. * * * ### Exercise 3 練習3 Write an appropriately general set of functions that can draw shapes as in Figure 4.2. > 寫一系列的合適的函數組合,畫出圖4.2所示的形狀。 Solution 樣例: http://thinkpython2.com/code/pie.py. ### Exercise 4 練習4 The letters of the alphabet can be constructed from a moderate number of basic elements, like vertical and horizontal lines and a few curves. Design an alphabet that can be drawn with a minimal number of basic elements and then write functions that draw the letters. > 字母表當中的字母都可以用一定數量的基本元素來構建,比如豎直或者水平的線條,以及一些曲線。設計一個能用最小數量的基本元素畫出來的字母表,然后寫個函數來畫字母出來。 You should write one function for each letter, with names draw_a, draw_b, etc., and put your functions in a file named letters.py. You can download a “turtle typewriter” from [this link](http://thinkpython2.com/code/typewriter.py) to help you test your code. > 你應當為沒一個字母寫一個函數,名字就比如draw_a,draw_b等等,然后把你的函數放到一個叫做letters.py的文件中。你可以從這個[鏈接](http://thinkpython2.com/code/typewriter.py) 下載一個烏龜打字機來幫你檢測一下代碼。 You can get a solution from [here](http://thinkpython2.com/code/letters.py); it also requires [this](http://thinkpython2.com/code/polygon.py). > 你可以參考這里的[樣例](http://thinkpython2.com/code/letters.py);同時還需要[這些](http://thinkpython2.com/code/polygon.py)。 ## Exercise 5 練習5 Read about spirals at [Wiki](http://en.wikipedia.org/wiki/Spiral); then write a program that draws an Archimedian spiral (or one of the other kinds). [Solution](http://thinkpython2.com/code/spiral.py) > 去[Wiki百科](http://en.wikipedia.org/wiki/Spiral)看一下螺旋線的相關內容;然后寫個程序來畫阿基米德曲線(曲線中的一種)。[樣例](http://thinkpython2.com/code/spiral.py)
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看