Python将索引设置为超出范围

2024-06-16 09:16:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我从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)   

Tags: 函数selfreturnifdefrespianome
2条回答

您可以在OOP中编写自变量:

>> (self.iniciar)

没有selfiniciar是一个全局变量

问题的根本原因在于以下两种说法:

  1. self.recente[-1]->;试图获取不存在的数组元素

  2. b = self.resp_nome(b)->;在初始化之前引用b

可以通过以下步骤解决问题:

  1. 将语句转换为验证数组中是否存在特定值的条件

    if 'Olá, qual seu nome?' not in self.recente:

  2. 将自我保护名称(b)替换为自我保护名称(a)

以下是实施了两项更改的工作示例:

# 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

相关问题 更多 >