2016-03-20 394 views
0

我正在閱讀Python教程,其中一個練習讓我卡住了。這個練習的描述是:「閱讀下面的函數,看看你能不能找出它的作用,然後運行它。」所以我無法真正告訴你它在做什麼,我仍在努力。AttributeError:'int'object has no attribute'fd'

我只寫了兩行第一行,它是來自上述教程的複製粘貼。下面是代碼:

import turtle 

t = turtle.Turtle() 
turtle.mainloop() 

def draw(t, length, n): 
    if n == 0: 
     return 
    angle = 50 
    t.fd(length*n) 
    t.lt(angle) 
    draw(t, length, n-1) 
    t.rt(2*angle) 
    draw(t, length, n-1) 
    t.lt(angle) 
    t.bk(length*n) 

draw(5, 10, 15) 

給出了回溯:

> Traceback (most recent call last): File 
> "D:\Directory\Python\Projects\Learning python\Exercises\Exercise 
> 5.14.5.py", line 18, in <module> 
>  draw(5, 10, 15) File "D:\Directory\Python\Projects\Learning python\Exercises\Exercise 5.14.5.py", line 10, in draw 
>  t.fd(length*n) AttributeError: 'int' object has no attribute 'fd' 
+1

傳遞給'draw'調用第一個參數是一個整數 - 't'。這個參數掩蓋了你的全局變量't = turtle.Turtle()' –

+0

@Rogalski我認爲你應該將它作爲答案 – syntonym

回答

1

你得到這個錯誤的原因是因爲第一個參數是5,所以變量t在函數的值5。該代碼然後嘗試呼叫5.fd(length*n)。調用draw當第一個參數切換到t

draw(t, 10, 15) 
相關問題