Python from turtle import *和import turtle的区别

Python from turtle import * and import turtle difference

我正在尝试使用一本关于 python 的书,我知道 from turtle import * 将所有内容导入当前命名空间,而 import turtle 只是引入模块以便可以调用作为 class。但是,当我尝试后者时,它坏了。

>>> 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

但是,使用 from turtle import*,将 pen 分配给对象并键入命令 forward 可以正常工作。这不是书上说要做的,但这是唯一有效的方法。发生了什么事?

如果书上这样说:

import turtle
t = turtle.pen()
t.forward(10)

那么这可能是一个错字:

import turtle
t = turtle.Pen()
t.forward(10)

其中 PenTurtle 的同义词——我们以前在这里见过这个问题。 (小写字母 pen() 是一个实用函数,除非出错,否则很少使用。)

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

我的建议:两者都不用。相反:

from turtle import Screen, Turtle

screen = Screen()
turtle = Turtle()

turtle.forward(10)
# ...
screen.exitonclick()

原因是 Python turtle 公开了两个编程接口,一个 functional 一个(对于初学者)和一个 object-oriented 一个。 (功能接口在库加载时从面向对象的接口派生而来。)使用任何一个都很好,但同时使用两者会导致混淆和错误。上面的导入提供了对面向对象接口的访问并阻止了功能接口。