2015-11-28 86 views
1

我只是學習使用「Think Python」一書的代碼,我很困惑。我遇到的問題是在TurtleWorld中創建鮮花。我創建的功能在他們的要求上不一致。首先,我發佈的成品,實際工作:功能不一致的要求

from swampy.TurtleWorld import* 

world=TurtleWorld() 
bob=Turtle() 
print bob 
bob.delay=.001 

def polyline(t,n,length,angle): 
    t=Turtle 
    print t 
    for i in range(n): 
     fd(bob,length) 
     lt(bob,angle) 

def arc(t, r, angle): 
    t=Turtle 
    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) 

def petal(t,r,angle): 
    for i in range(2): 
     arc(t,r,angle) 
     lt(t,180-angle) 

def flower(t, n, r, angle): 
    t=Turtle 
    for i in range(n): 
     petal(bob,r,angle) 
     lt(bob,360/n) 

flower(bob,5,77,99) 

wait_for_user 

arcpetal函數定義,t足夠了烏龜,雖然當我開始,在flower定義使用tpolyline返回一個錯誤未綁定的方法(fd和lt)。需要烏龜實例,取而代之的是類型實例。

t=Turtleprint turtle添加到一半的函數定義後,添加了事實後嘗試修復此錯誤。這是工作版本,我只想知道爲什麼它以前沒有工作。我甚至不知道爲什麼這會起作用,因爲我主要把bob作爲t出於沮喪,我沒有真正期待它的工作。

+0

'BOB =龜()''套到bob'評估龜函數的結果。嘗試'bob = Turtle'(注意不要使用圓括號)並刪除t中的函數分配。 – mpez0

回答

0

儘管我在下面使用Python提供的龜類庫,而不是swampy.TurtleWorld,但我認爲這對您遇到的問題沒有什麼影響。您似乎對函數調用中的形式參數以及函數調用和方法調用之間的區別存在基本的誤解。考慮這一系列事件:

flower(bob,5,77,99) 
def flower(t, n, r, angle): 
    t=Turtle 
    ... 

這裏一個非常好的甲魚,bob,被傳遞的像烏龜一樣的說法t只能用別的東西立即更換。或者考慮polyline,它有一個烏龜參數t,但是當需要一隻烏龜時使用全局碼bob。以下是我想象你的程序應該走到一起:

from turtle import Turtle, Screen 
from math import pi 

def polyline(turtle, n, length, angle): 
    for _ in range(n): 
     turtle.fd(length) 
     turtle.lt(angle) 

def arc(turtle, radius, angle): 
    arc_length = 2 * pi * radius * angle/360 
    n = int(arc_length/3) + 1 
    step_length = arc_length/n 
    step_angle = float(angle)/n 
    polyline(turtle, n, step_length, step_angle) 

def petal(turtle, radius, angle): 
    for _ in range(2): 
     arc(turtle, radius, angle) 
     turtle.lt(180 - angle) 

def flower(turtle, n, radius, angle): 
    for _ in range(n): 
     petal(turtle, radius, angle) 
     turtle.lt(360/n) 

screen = Screen() 

bob = Turtle() 

flower(bob, 5, 77, 99) 

screen.exitonclick() 

輸出

enter image description here