我正在尝试搁置模块,但遇到了一些麻烦。我的意图是让一个模块在第二个模块中调用一个函数,该函数将修改搁置中的文件。我制作了一个原型(如下),它只是尝试将变量设置为存储在搁架中的内容并打印该对象。
当我尝试这样做时,我收到以下属性错误:
AttributeError: 'module' object has no attribute 'User'
我的猜测是它没有意识到我的“用户”类存在,但我不确定原因。File1 在它的 main 函数中调用与 File2 相同的函数,并且它在该实例中正常工作。我很感激这个问题的任何帮助,我对问题是什么感到困惑。
import SE_ex2
SE_ex2.cacheTest()
import shelve
cache_users = shelve.open("usersTest.cache")
class User(object):
def __init__(self, name, num):
self.name = name
self.num = num
def __str__(self):
return "Name:{0}, Num={1}".format(self.name, self.num)
def cacheTest():
obj = cache_users[ "user_red" ]
print obj
if __name__ == "__main__":
cacheTest()
#Used for creating the cache for the first time
# red = User("red", 11)
# green = User("green", 22)
# blue = User("blue", 33)
#
# cache_users['user_red'] = red
# cache_users['user_green'] = green
# cache_users['user_blue'] = blue
# print "DONE"
完整追溯:
Traceback (most recent call last):
File "C:\Users\akaGrim\My Documents\Aptana Studio 3 Workspace\ShelveTest\SE_ex1.py", line 3, in <module>
SE_ex2.cacheTest()
File "C:\Users\akaGrim\My Documents\Aptana Studio 3 Workspace\ShelveTest\SE_ex2.py", line 14, in cacheTest
obj = cache_users[ "user_red" ]
File "C:\Python27\lib\shelve.py", line 122, in __getitem__
value = Unpickler(f).load()
AttributeError: 'module' object has no attribute 'User'