问题是你把你的程序命名为“turtle.py”。
所以当Python看到语句
from turtle import *
它找到的第一个名为turtle的匹配模块是您的程序“turtle.py”。
换句话说,你的程序基本上是自己导入,而不是海龟图形模块。
这里有一些代码来演示这个问题。
海龟.py#! /usr/bin/env python
''' Mock Turtle
Demonstrate what happens when you give your program the same name
as a module you want to import.
See http://stackoverflow.com/q/32180949/4014959
Written by PM 2Ring 2015.08.24
'''
import turtle
foo = 42
print(turtle.foo)
help(turtle)
我想我应该展示代码实际打印的是什么。。。
当运行方式为turtle.py时,它会打印以下“帮助”信息: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 http://stackoverflow.com/q/32180949/4014959
Written by PM 2Ring 2015.08.24
DATA
foo = 42
(END)
当您点击Q退出帮助时,将再次显示帮助信息。当你第二次点击Q时,那么42
42
是印刷品。
为什么“帮助”信息和42个打印两次?这是因为turtle.py中的所有代码在导入时执行,然后在import语句之后遇到时再次执行。请注意,Python不会尝试导入它已经导入的模块(除非明确告知使用reload这样做)。如果Python确实重新导入,那么上面的代码将陷入导入的无限循环中。
当作为mockturtle.py运行时,它会打印:Traceback (most recent call last):
File "./mock_turtle.py", line 16, in
print(turtle.foo)
AttributeError: 'module' object has no attribute 'foo'
当然,这是因为标准的turtle模块实际上没有foo属性。