【问题标题】:Python 2: AttributeError: 'module' object has no attribute 'scan'Python 2:AttributeError:“模块”对象没有属性“扫描”
【发布时间】:2018-07-31 20:21:39
【问题描述】:

我目前正在通过“Learn python the hard way”一书学习 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')

是我在导入时做错了什么还是扫描函数的语法有误?

【问题讨论】:

    标签: python import attributeerror


    【解决方案1】:

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

    编辑: 我明白了,您在名为lexicon 的模块中有一个名为Lexicon 的类。你必须先初始化你的类,然后调用函数:

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

    【讨论】:

    • 我已经有一个 init.py,是一样的吗?此外,删除“自我”后,我仍然收到错误消息。 link to the full lexicon.py
    • 哦,我明白了,你有下划线。但是,是的,我有那个文件。
    • 你可以保留“self”参数,但你必须这样称呼它: lex = lexicon.Lexicon() lex.scan("north south")
    • @squeezyPig 除非有充分的理由拥有Lexicon 类,否则如果将scan 方法移到Lexicon 类之外(并删除self),您的代码会更简单,比如this example
    【解决方案2】:

    错误的使用 self 是什么给你的问题: https://pythontips.com/2013/08/07/the-self-variable-in-python-explained/

    def scan(input):
        ....
    

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

    【讨论】:

    猜你喜欢
    • 2015-03-09
    • 2013-07-05
    • 2011-10-25
    • 2017-09-02
    • 2014-07-24
    • 2015-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多