Python 2:AttributeError:'module'对象没有属性'scan'

时间:2018-02-21 09:50:01

标签: python import attributeerror

我目前正在使用“学习python的方式”这本书学习Python,我收到了一个错误。

我有一个名为ex48的文件夹,其中有一个lexicon.py。在这个lexicon.py我有'扫描'功能,它获取一个输入,拆分并识别单词,然后返回一个列表。:

def scan(self, input):
    identifiedWords = []
    words = input.split(" ")
    for i in len(words):
        # check if it's a number first
        try:
            identifiedWords[i] = ('number', int(words[i]))
        except ValueError:
            # directions
            if words[i].lower() == 'north':
                identifiedWords[i] = ('direction', 'north')
            elif words[i].lower() == 'east':
                identifiedWords[i] = ('direction', 'east')

...

            # error
            else:
            identifiedWords[i] = ('error', words[i])

    return identifiedWords

在我的ex48文件夹之外我试图在powershell中使用此功能。 我在做:

>>> from ex48 import lexicon
>>> lexicon.scan("north south")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'scan'
>>>

功能返回[('direction', 'north'), ('direction', 'south')

导入错误或扫描功能的语法是错误的吗?

2 个答案:

答案 0 :(得分:1)

要将ex48标记为Python模块,您必须创建一个名为__init__.py的空文件 此外,scan方法包含参数“self”,这使它成为一个类方法。您必须在使用该方法之前初始化该类。

编辑: 我知道,在名为Lexicon的模块中有一个名为lexicon的类。你必须首先启动你的类,然后调用函数:

from ex48 import lexicon
lex = lexicon.Lexicon()
lex.scan("north south")

答案 1 :(得分:0)

错误使用自我是什么让你遇到问题: https://pythontips.com/2013/08/07/the-self-variable-in-python-explained/

def scan(input):
    ....

应该解决它。链接是了解原因。