【发布时间】:2023-01-19 15:10:12
【问题描述】:
我有一个无法调用运行的程序,我尝试从 spellCheck.py 调用 linearSearch() def。有人能帮我理解为什么我的代码给我一个 AttributeError 吗?我不明白为什么调用 initial.linearSearch(choice) 不会给我任何东西。
拼写检查.py:
class SpellCheck():
def __init__(self):
try:
open("dictionary.txt", "r")
except FileNotFoundError:
print("Dictionary file not found")
else:
#store all elements in a list
dictionary = []
#open dictionary.txt
with open("dictionary.txt", "r") as f:
for line in f:
dictionary.append(line.strip())
def binarySearch(self, word):
steps = 0
low = 0
high = len(dictionary) - 1
while low <= high:
middle = (low + high) // 2
if(dictionary[middle] == word):
steps += 1
return (f"{bcolors.OKGREEN}Found {bcolors.BOLD}{word}{bcolors.ENDC}{bcolors.OKGREEN} after {steps} steps!{bcolors.ENDC}")
elif (dictionary[middle] < word):
steps += 1
low = middle + 1
else:
steps += 1
high = middle - 1
return(f"{bcolors.FAIL}The word {bcolors.BOLD}{word}{bcolors.ENDC}{bcolors.FAIL} wasn't found!{bcolors.ENDC}")
def linearSearch(word):
steps = 0
for i in range(len(dictionary)):
steps += 1
if dictionary[i] == self.word:
steps += 1
return(f"{bcolors.OKGREEN}Found {bcolors.BOLD}{self.word}{bcolors.ENDC}{bcolors.OKGREEN} after {steps - 1} steps!{bcolors.ENDC}")
return(f"{bcolors.FAIL}The word {bcolors.BOLD}{self.word}{bcolors.ENDC}{bcolors.FAIL} wasn't found!{bcolors.ENDC}")
#color coding for terminal
#source: https://stackoverflow.com/a/287944
#either True or False
class bcolors:
BOLD = '\033[1m'
OKGREEN = '\033[92m'
FAIL = '\033[91m'
ENDC = '\033[0m'
YELLOW = '\033[93m'
#debug statement
#if debug == True:
#print(f"Debug Colors:\n{BOLD}BOLD{ENDC}\n{OKGREEN}OKGREEN{ENDC}\n{FAIL}FAIL{ENDC}\n{YELLOW}YELLOW{ENDC}")
#end of color codes
主程序
from spellCheck import SpellCheck
#from spellCheck import bcolors
def main():
choice = input("Enter the word to look for:\n> ")
initial = SpellCheck()
initial.__init__()
initial.linearSearch(choice)
main()
这是终端的输出:
Enter the word to look for:
> apple
Traceback (most recent call last):
File "main.py", line 11, in <module>
main()
File "main.py", line 8, in main
initial.linearSearch(choice)
AttributeError: 'SpellCheck' object has no attribute 'linearSearch'
【问题讨论】:
-
您的函数定义为
__init__,不是该类的属性。取消缩进那些功能 -
1. 在
initial = SpellCheck()中创建对象时调用__init__。 2. 所有类函数都缩进太多,而是在__init__中定义。 -
不止于此你不应该打电话在里面在您已经编写 SpellCheck() 之后。在里面当您创建 SpellCheck 类的实例时将自动调用
-
您可以尝试 PyCharm 或 VS 代码之类的 IDE。两者都是免费的,但 VS 代码需要更多配置。它将通过标记您的错误来帮助您。
标签: python python-3.x attributeerror