Python 3.1.1 中的搁置模块
我是 Python 新手,正在通过 O'Reilly“学习 Python”系列进行学习。我被困在一个搁置的示例中,无法弄清楚为什么该程序不起作用。我正在尝试构建一些示例数据,然后将其加载到搁置文件中。奇怪的是,当我将其输入到 IDLE shell 中时它会起作用,但当我将其输入到 .py 文件并尝试运行它时却不起作用。这是我的代码:
from Python_Learning.person import Person, Manager
bob = Person('Bob Smith', 'dev', 60000)
sue = Person('Sue Jones', job = 'designer', pay = 100000)
tom = Manager('Tom Jones', 1000000)
import shelve
db = shelve.open('persondb')
for object in (bob, sue, tom):
db[object.name] = object
db.close()
同样,当我在 IDLE shell 上运行此代码时,没有问题,但是当我从 .py 文件运行时,出现以下错误:
回溯(最近一次调用最后一次): 文件“Documents/Python_Learning/shelve.py”,第 7 行,位于 进口货架 文件“Documents/Python_Learning/shelve.py”,第 9 行,位于 db = shelve.open('persondb') AttributeError:“模块”对象没有属性“打开”
如果有帮助,这里是我在 Snow Leopard 上运行的 Python 版本的信息:
Python 3.1.1 (r311:74543,2009 年 8 月 24 日,18:44:04 ) [GCC 4.0.1 (Apple Inc. build 5493)] on darwin
感谢您对新手的帮助!
将要
I'm new to Python and learning through the O'Reilly "Learning Python" series. I'm stuck on a shelve example and can't figure out why the program doesn't work. I'm trying to build some sample data and then load it into a shelve file. The weird thing is that it works when I type it into the IDLE shell but not when I type it into a .py file and try to run it. Here's my code:
from Python_Learning.person import Person, Manager
bob = Person('Bob Smith', 'dev', 60000)
sue = Person('Sue Jones', job = 'designer', pay = 100000)
tom = Manager('Tom Jones', 1000000)
import shelve
db = shelve.open('persondb')
for object in (bob, sue, tom):
db[object.name] = object
db.close()
Again, when I run this code on an IDLE shell, I have no problem, but when I run from a .py file I get the following error:
Traceback (most recent call last):
File "Documents/Python_Learning/shelve.py", line 7, in
import shelve
File "Documents/Python_Learning/shelve.py", line 9, in
db = shelve.open('persondb')
AttributeError: 'module' object has no attribute 'open'
In case it helps, here's the info on the Python version I'm running on Snow Leopard:
Python 3.1.1 (r311:74543, Aug 24 2009, 18:44:04)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Thanks for your help to a newbie!
Will
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将您的模块重命名为
shelve.py
之外的其他名称 - 您正在导入自己。Rename your module to something else than
shelve.py
— you're importing yourself.