问题在于你将程序命名为"turtle.py"。
因此,当Python遇到语句
from turtle import *
第一个匹配的名为
turtle
的模块是
你自己的程序,即"turtle.py"。
换句话说,你的程序基本上是在导入自己,而不是海龟图形模块。
下面的代码演示了这个问题。
turtle.py
''' Mock Turtle
Demonstrate what happens when you give your program the same name
as a module you want to import.
See https://dev59.com/i47ea4cB1Zd3GeqPAmaP
Written by PM 2Ring 2015.08.24
'''
import turtle
foo = 42
print(turtle.foo)
help(turtle)
我猜我应该展示一下那段代码实际上会打印什么...
当作为 turtle.py
运行时,它会输出以下的 "help" 信息:
Help on module turtle:
NAME
turtle - Mock Turtle
FILE
/mnt/sda4/PM2Ring/Documents/python/turtle.py
DESCRIPTION
Demonstrate what happens when you give your program the same name
as a module you want to import.
See https://dev59.com/i47ea4cB1Zd3GeqPAmaP
Written by PM 2Ring 2015.08.24
DATA
foo = 42
(END)
当您按下 Q
键退出帮助时,帮助信息将再次显示。第二次按下 Q
键,则...
42
42
打印出来了。
为什么“help”信息和42被打印了两次?这是因为在导入turtle.py
时,其中的所有代码都会被执行,然后在import
语句之后再次执行。请注意,Python不会尝试导入已经导入的模块(除非使用reload
显式告诉它这样做)。如果Python重新导入模块,则上述代码将陷入无限循环的导入中。
以mockturtle.py
运行时,它会打印:
Traceback (most recent call last):
File "./mock_turtle.py", line 16, in <module>
print(turtle.foo)
AttributeError: 'module' object has no attribute 'foo'
当然,这是因为标准的turtle
模块实际上没有foo
属性。
turtle.py
是你的程序名称。是这样吗? - PM 2Ringpen
而不是Pen
,另外我认为你不能将多个笔存储为对象。 - SuperBiasedManpen()
是一个用于与唯一存在的笔属性交互的函数。 - SuperBiasedMan