![](/img/trans.png)
[英]Python: AttributeError: 'module' object has no attribute 'socketpair'
[英]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.