簡體   English   中英

Python 2:AttributeError:“模塊”對象沒有屬性“掃描”

[英]Python 2: AttributeError: 'module' object has no attribute 'scan'

我目前正在通過“艱苦學習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文件夾之外,我試圖在ex48中使用此功能。 我正在做:

>>> 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')

我在導入時做錯什么了嗎,或者掃描函數的語法錯了嗎?

要將ex48標記為Python模塊,您必須創建一個名為__init__.py的空文件。scan方法還包含參數“ self”,這使其成為類方法。 您必須在使用方法之前初始化類。

編輯:我看到,您在名為lexicon的模塊內有一個名為Lexicon的類。 您必須首先初始化您的類,然后調用該函數:

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

錯誤使用self會給您帶來問題: https : //pythontips.com/2013/08/07/the-self-variable-in-python-explained/

def scan(input):
    ....

應該解決它。 鏈接是為了了解原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM