python中的turtle模块_python中的Turtle模块未导入

问题是你把你的程序命名为“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属性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值