我正在运行Python 3,并且我收到以下错误:
AttributeError: 'AssemblyParser' object has no attribute 'hasMoreCommands'
以下是引发错误的代码:
import sys
from Parser import AssemblyParser
from Code import Code
parser = AssemblyParser(sys.argv[1])
translator = Code()
out_file = str(sys.argv[1]).split(".")
out_file = str(out_file[:1]) + ".hack"
with open(out_file, 'w', encoding='utf-8') as f:
while parser.hasMoreCommands():
parser.advance()
if parser.commandType() == "A_COMMAND":
dec_num = parser.symbol()
binary = "{0:b}".format(dec_num)
elif parser.commandType() == "C_COMMAND":
default_bits = "111"
comp_bits += translator.comp(parser.comp())
dest_bits += translator.dest(parser.dest())
jump_bits += translator.jump(parser.jump())
binary = default_bits + comp_bits + dest_bits + jump_bits
assert len(binary) == 16
f.write(binary)
这是我的Parser.py文件:
class AssemblyParser:
"""
Encapsulates access to the input code. Reads an assembly language command,
parses it, and provides convenient access to the command's components (fields and symbols).
In addition, removes all whitespace and comments.
"""
def __init__(self, input_file):
self.current_command = ""
self.next_command = ""
with open(input_file,"r+", encoding='utf-8') as f:
for l in f:
line = "".join(l.split()) # Remove whitespace from the line
line = line.split('//') # Removes any comments from the line
clean_line = line[0]
if clean_line.strip(): # Removes any blank lines
f.write(clean_line)
next_command = f.readline()
def __hasMoreCommands__(self):
if self.next_command:
return true
return false
def __advance__(self):
with open(input_file, encoding='utf-8') as f:
self.current_command = self.next_command
self.next_command = f.readline()
def __commandType__(self):
char_1 = self.current_command[:1]
if char_1 == "@":
return "A_COMMAND"
elif char_1 == "(":
return "L_COMMAND"
else:
return "C_COMMAND"
def __symbol__(self):
assert self.commandType() == ("A_COMMAND" or "L_COMMAND")
if self.commandType() == "A_COMMAND":
symbol = str(symbol[1:])
else:
symbol = str(symbol[1:len(symbol)-1])
return str(symbol)
def __dest__(self):
assert self.commandType() == "C_COMMAND"
if "=" in self.current_command:
temp = self.current_command.split("=")
return str(temp[:1])
else:
return ""
def __comp__(self):
assert self.commandType() == "C_COMMAND"
temp = self.current_command
if "=" in temp:
temp = temp.split("=")
temp = str(temp[1:])
if ";" in temp:
temp = temp.split(";")
temp = str(temp[:1])
return temp
def __jump__(self):
assert self.commandType() == "C_COMMAND"
if ";" in self.current_command:
temp = self.current_command.split(";")
return str(temp[1:])
else:
return ""
我真的不知道为什么我会收到此错误,我查看了导入文档,但我越来越困惑。我对Python很新。任何人都可以解释这个错误吗?
感谢。
答案 0 :(得分:1)
好。在具有名称hasMoreCommand的Parser模块中似乎没有任何功能。那里的函数以下划线开头,并以下划线结尾。
答案 1 :(得分:0)
两个前导和尾随下划线用于标识“魔术”属性。您不能使用它来创建自己的,因为它们只引用预先存在的方法。
以下是您可能想要的内容:
hasMoreCommands():
如果您有多个具有此功能的类,请改用名称修改:
_hasMoreCommands():