Issue
I am trying to use a book on python, and I understand that from turtle import *
imports everything into the current namespace while import turtle
just brings the module in so it can be called as a class. When I try the latter, though, it breaks.
>>> import turtle
>>> t = turtle.pen()
>>> t.pen.forward(10)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
t.pen.forward(10)
AttributeError: 'dict' object has no attribute 'pen
However, using from turtle import*
, assigning pen
to an object and typing command forward
works fine. This is not what the book says to do, but it is the only thing that works. What is happening?
Solution
If the books says something like:
import turtle
t = turtle.pen()
t.forward(10)
then it's probably a typo for:
import turtle
t = turtle.Pen()
t.forward(10)
where Pen
is a synonym for Turtle
-- we've seen that problem here before. (Lowercase pen()
is a utility function that's rarely used except in error.)
I understand that
from turtle import *
imports everything into the current namespace whileimport turtle
just brings the module in so it can be called as a class
My recommendation: use neither. Instead do:
from turtle import Screen, Turtle
screen = Screen()
turtle = Turtle()
turtle.forward(10)
# ...
screen.exitonclick()
The reason is that Python turtle exposes two programming interfaces, a functional one (for beginners) and an object-oriented one. (The functional interface is derived from the object-oriented one at library load time.) Using either is fine but using both at the same time leads to confusion and bugs. The above import gives access to the object-oriented interface and blocks the funcitonal one.
Answered By - cdlane
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.