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

我编写的这段Python Calculator类代码是否存在错误?

代码错误排查与修正

你的这段代码存在变量名不一致的错误:

  • 在__init__方法里,你把传入的参数赋值给了self.number
  • 但在square方法的格式化字符串中,错误使用了未定义的self.num,运行时会抛出AttributeError

修正后的代码如下:

class Calculator:
    def __init__(self, num):
        self.number = num
    
    def square(self):
        print(f"The Square value of {self.number} is {self.number**2}")

a = Calculator(3)
a.square()

运行修正后的代码,会输出The Square value of 3 is 9,符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 15:40:41