如何解决Python Acuses索引超出范围
我从Python开始,直到进入课程部分为止,我一直表现不错。好吧,我正在尝试创建一个ChatBot,在主类中,函数Python pensar()
返回iniciar
,因此函数resp()
可以将其附加到self.recente列表中。它按原样发生,但是当循环再次到达pensar()
时,它不会获得self.recente [-1]。希望有人能帮助我。
这是课程代码:
class IA():
def __init__(self,nome):
self.nome = nome
self.recente = []
def ouvir(self):
iniciar = input('»')
iniciar = iniciar.upper()
iniciar = iniciar.replace('O ','')
return iniciar
def pensar(self,iniciar):
if iniciar == 'OI':
return 'Ola,qual seu nome?'
if self.recente[-1] == 'Olá,qual seu nome?':
a = self.pegar_nome()
b = self.resp_nome(b)
def pegar_nome(self):
pass
def resp_nome(self,iniciar):
pass
def resp(self,iniciar):
self.recente.append(iniciar)
print(iniciar)
这是main.py之一:
from Ia import IA
tchau = ['TCHAU','XAU','ATE LOGO','ATÉ LOGO','ATE MAIS','ATÉ MAIS']
while True:
a = IA('Joao')
b = a.ouvir()
if b in tchau:
print('Até mais')
break
c = a.pensar(b)
a.resp(c)
解决方法
问题的根本原因在于以下两个语句:
-
self.recente[-1]
--->试图获取不存在的数组元素。 -
b = self.resp_nome(b)
--->在初始化之前引用b。
可以通过以下步骤解决问题:
-
将语句转换为验证数组中是否存在特定值的条件。
即
if 'Olá,qual seu nome?' not in self.recente:
-
将self.resp_nome(b)替换为self.resp_nome(a)
以下是实现了2个更改的工作示例:
# File name: python-class-demo.py
class IA():
def __init__(self,nome):
self.nome = nome
self.recente = []
def ouvir(self):
iniciar = input('»')
iniciar = iniciar.upper()
iniciar = iniciar.replace('O ','')
return iniciar
def pensar(self,iniciar):
if iniciar == 'OI':
return 'Ola,qual seu nome?'
if 'Olá,qual seu nome?' not in self.recente:
a = self.pegar_nome()
b = self.resp_nome(a)
def pegar_nome(self):
pass
def resp_nome(self,iniciar):
pass
def resp(self,iniciar):
self.recente.append(iniciar)
print(iniciar)
tchau = ['TCHAU','XAU','ATE LOGO','ATÉ LOGO','ATE MAIS','ATÉ MAIS']
while True:
a = IA('Joao')
b = a.ouvir()
if b in tchau:
print('Até mais')
break
c = a.pensar(b)
a.resp(c)
输出:
>python python-class-demo.py
»as
None
»OU
None
»TCHAU
Até mais
,
您可以在OOP中编写自变量:
>> (self.iniciar)
没有self
,iniciar
是全局变量
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。