Python 'module'对象是不可调用的问题,尝试以几种不同的方式导入模块



我最近接管了一个用Python编写并使用web.py的网站的维护工作。我已经创建了一个想要导入的类,但我收到了"TypeError:'module'object is not callable"错误。所有.py模块都存储在一个名为"lib"的目录中。lib目录中有以下模块:noun.py、verb.py、context.py、word.py、base.py。lib目录中是--init--.py文件。我正在尝试将noun.py模块导入上下文模块。下面是context.py模块中用于导入其他模块的代码。

from lib import verb, word, base

这似乎适用于导入动词、单词和基本模块。但当我在陈述的末尾加上名词使其…

from lib import, verb, word, base, noun

我得到"TypeError:'module'对象不可调用"错误。我也试过。。。

import noun #Also produces the same error

所以我尝试了以下。。。

from noun import *

当我以这种方式导入模块时,错误会被消除,但当我引用名词模块的属性时,我会得到错误"AttributeError:noon instance没有属性'get_stem_used'"。下面是名词模块的代码。。。

from base import base
class noun:
wordBase = None
stemBase = None
def __init__(self, pId):
b = base()
wrdBase = b.get_word_base(pId)
self.wordBase = wrdBase['base']
stmBase = b.get_stemBase(pId)
self.stemBase = stmBase['stem']
#Code to make sure the module is instantiated correctly and the data is validated
def get_output(self):
return self.wordBase
def get_stem_used(self):
return self.stemBase

verb.py模块的代码与noun.py模块的代码基本相同。在context.py模块中,我有以下代码。。。

n = noun(id)
base = n.get_output()
#I print out base to make sure everything is good and it is
v = verb(id)
verb = v.get_output()

然后将"n"one_answers"v"传递给word.py模块。在word.py模块中有以下代码。

if v.get_stem_used == "Some Value":
#do whatever
elif n.get_stem_used == "Another value":  #This line produces the "attribute error"
#do something

当我尝试访问n.get_stem_used时,我会得到"AttributeError:nonn实例没有属性'get_stem_used'"错误。我做了一些研究,发现了这个网址http://effbot.org/zone/import-confusion.htm这让我相信我没有正确导入名词模块,因为我没有使用以下代码导入名词模块。。。它不允许我使用点表示法来引用名词类中的元素。

from lib import, verb, word, noun

奇怪的是,在上面的语句末尾添加"名词"不起作用,但它似乎正确地导入了所有其他模块。我已经看到混合使用制表符和空格可能会导致这个错误,但我已经使用编辑器检查了它是否是正确的制表符。我已经为此工作了一段时间,所以我们非常感谢您的帮助。谢谢

下面是--init--.py 中的内容

#!/usr/local/bin/python2.5
# -*- coding: utf-8 -*-

类和模块之间似乎存在混淆。你说你在做from lib import noun,然后是n = noun(id)。这就是错误的来源:这里的noun指的是名词模块,而不是该模块内的名词类。Java不是Python:类是与其模块分开的可导入名称,它们不必与所在的模块具有相同的名称,并且一个模块中可以有多个类。

所以,你要么需要做:

from lib import noun
n = noun.noun(id)

from lib.noun import noun
n = noun(id)

(顺便说一句,如果您使用符合PEP8的名称,这将是显而易见的:您将导入noun,但实例化Noun。)

其他"非Java"点:不需要get_outputget_stem_used方法,只需直接引用wordBasestemBase即可。但是,如果你有这些方法,你需要在比较中实际调用它们:if n.get_stem_used() == "Another value"等等

最新更新