我从Python开始学习,在开始学习类之前,我一直做得很好。我正在尝试创建一个聊天机器人,在主类中,函数Pythonpensar()
返回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)
这是最主要的一个:
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)
您可以在OOP中编写自变量:
没有
self
,iniciar
是一个全局变量问题的根本原因在于以下两种说法:
self.recente[-1]
->;试图获取不存在的数组元素b = self.resp_nome(b)
->;在初始化之前引用b可以通过以下步骤解决问题:
将语句转换为验证数组中是否存在特定值的条件
即
if 'Olá, qual seu nome?' not in self.recente:
将自我保护名称(b)替换为自我保护名称(a)
以下是实施了两项更改的工作示例:
输出:
相关问题 更多 >
编程相关推荐