[英]Python 2: AttributeError: 'module' object has no attribute 'scan'
I'm currently learning Python with the book "Learn python the hard way" and I'm getting an error. 我目前正在通过“艰苦学习python”这本书来学习Python,但遇到错误。
I have a folder called ex48
where a lexicon.py
is located. 我有一个名为ex48
的文件夹,其中有一个lexicon.py
。 In this lexicon.py
I have 'scan' function, which gets one input, splits it and identifies the words, then returns a list.: 在这个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
Outside of my ex48
folder I'm trying to use this function in powershell. 在我的ex48
文件夹之外,我试图在ex48
中使用此功能。 I'm doing: 我正在做:
>>> 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'
>>>
The function should return [('direction', 'north'), ('direction', 'south')
该函数应返回[('direction', 'north'), ('direction', 'south')
Am I doing something wrong with the import or is the syntax of the scan function wrong? 我在导入时做错什么了吗,或者扫描函数的语法错了吗?
To mark ex48 as a Python module, you have to create an empty file called __init__.py
Also, the scan method contains the argument "self", which makes it a class method. 要将ex48标记为Python模块,您必须创建一个名为__init__.py
的空文件。scan方法还包含参数“ self”,这使其成为类方法。 You have to initialize the class before using the method. 您必须在使用方法之前初始化类。
Edit: I see, you have a class called Lexicon
inside the module called lexicon
. 编辑:我看到,您在名为lexicon
的模块内有一个名为Lexicon
的类。 You have to first init your class and then call the function: 您必须首先初始化您的类,然后调用该函数:
from ex48 import lexicon
lex = lexicon.Lexicon()
lex.scan("north south")
Wrong usage of self is whats giving you the problem : https://pythontips.com/2013/08/07/the-self-variable-in-python-explained/ 错误使用self会给您带来问题: https : //pythontips.com/2013/08/07/the-self-variable-in-python-explained/
def scan(input):
....
should solve it. 应该解决它。 The link is to understand why. 链接是为了了解原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.