You need to enable JavaScript to run this app. Python自定义类调用portugues方法错误返回alimentos问题求助
优惠活动
大模型
产品
解决方案
定价
更多

Python自定义类调用portugues方法错误返回alimentos问题求助

问题原因
  • 你传入的courses_x字典仅包含alimentos键,没有português键,因此__init__构造方法里的for循环只会遍历到alimentos,循环变量被你定义成了实例属性self.p,循环结束后self.p就被永久赋值为alimentos,后续调用任何方法只要读取self.p都会拿到这个值。
  • 方法设计逻辑错误:alimentos、portugues两个方法完全依赖self.p获取目标学科名,没有和方法本身对应的学科绑定,导致方法输出完全由self.p的当前值决定,和方法的预期功能脱节。
解决方法

直接修改两个业务方法的逻辑,去掉对self.p的依赖,每个方法直接绑定对应的学科名,同时可以删掉构造方法里冗余的预调用逻辑(如果不需要预执行的话),修改后的代码参考:

class Disciplinas_cursos_1:
    "Define the disciplinas and professors"

    def __init__(self,cursos_,professores_):
        self.cursos_ = cursos_
        self.professores_ = professores_

    def alimentos(self):
        # 直接指定当前方法对应学科为alimentos
        target_disc = 'alimentos'
        profiel_prof_disc = self.professores_[target_disc]
        discipl_alimentos = [target_disc,[x['prof_id'] for x in profiel_prof_disc
                                                   if x['prof_disc'] == target_disc]]
        return discipl_alimentos

    def portugues(self):
        print("Now its portuguese turn")
        # 直接指定当前方法对应学科为português
        target_disc = 'português'
        profiel_prof_disc = self.professores_[target_disc]
        print(f"see I'm printing {target_disc}. It's that the same of portuguese? If' not it's wrong")
        discipl_port =[target_disc,[x['prof_id'] for x in profiel_prof_disc if x['prof_disc'] == target_disc]]
        print(f"see I'm printing {target_disc} and {discipl_port}")
        return discipl_port

修改后调用disc_a.portugues()就会返回预期的葡萄牙语学科相关结果。如果你确实需要保留构造方法里的预调用逻辑,记得给courses_x补上português对应的条目即可。

内容的提问来源于stack exchange,提问作者Renata Thomazelli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 17:57:00