You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python类方法报错AttributeError:SecretFormula无reveal_formula属性排查

问题分析与修复方案

错误点总结

  • 方法缩进错误:@classmethod装饰器和方法定义没有缩进在SecretFormula类的代码块内,导致该方法不属于类,调用时自然找不到reveal_formula属性。
  • 方法名拼写错误:作业要求的方法名是reveal_formula,但你写成了reveal__formula(多了一个下划线),和调用时的名称不匹配。
  • 返回值错误:密码正确时返回的是方法对象cls.reveal_formula,而不是私有配方属性cls.__formula。

修复后的代码

class SecretFormula:
    __formula = "C10H15N"

    @classmethod
    def reveal_formula(cls, passphrase):
        if passphrase == "Heisenberg":
            return cls.__formula    
        else:
            return "Nice try!"
    
print(SecretFormula.reveal_formula("Heisenberg"))
print(SecretFormula.reveal_formula("Gus Fring"))

运行结果

C10H15N
Nice try!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 10:33:10