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

如何修复Python代码中的NameError: name 'self' is not defined错误

错误原因及修复方案

核心错误分析

  • surface=self.surface这行代码完全多余,且写在类定义外部,此时self无定义,直接触发NameError。
  • surface、affichage两个方法缩进错误,未归属于Rectangle类,导致类无法识别这些方法。
  • 字符串拼接时,数字类型的属性(self.lon、self.lar、surface方法返回值)未转为字符串,会触发TypeError。
  • 直接打印实例对象会输出内存地址,无法展示实际属性信息。

修复后的完整代码

class Rectangle:
    def __init__(self, longueur=30, largeur=15):
        self.lon = longueur
        self.lar = largeur
        self.nom = "rectangle"

    def surface(self):
        return self.lon * self.lar

    def affichage(self):
        # 用f-string简化格式化,自动处理数字转字符串
        print(f"{self.nom}: longueur={self.lon}, largeur={self.lar}, surface={self.surface()}")

    # 定义__str__方法,让打印实例时显示有用信息
    def __str__(self):
        return f"{self.nom}: longueur={self.lon}, largeur={self.lar}, surface={self.surface()}"

class Carre(Rectangle):
    def __init__(self, cote=10):
        super().__init__(cote, cote)  # 用super()调用父类构造更规范
        self.nom = "carre"

r = Rectangle()
r.affichage()
print(r)

c = Carre()
c.affichage()
print(c)

关键修复点说明

  1. 修正方法缩进:将surface和affichage方法缩进,纳入Rectangle类内部,确保类能识别这些方法。
  2. 删除错误代码:移除surface=self.surface这行无意义且报错的代码。
  3. 修复字符串拼接:使用f-string格式化输出,避免数字与字符串直接拼接的类型错误。
  4. 优化父类调用:Carre类中用super().__init__()替代Rectangle.__init__(self, ...),写法更简洁且适配多继承场景。
  5. 添加__str__方法:让打印实例对象时直接输出属性信息,替代默认的内存地址展示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 14:20:34