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

Python继承代码异常求助:期望输出ram 22 KIIT但结果异常

问题排查与修复:Python继承中的构造函数调用错误

嘿,我帮你找到问题啦!你的代码里有个小错误藏在Student类的构造函数里,咱们一步步拆解:

错误原因

在Student类的__init__方法中,你写了super().__init__(self)——这是不对的。父类College的__init__方法接收的是可选的clgName参数,而super()已经自动帮你绑定了当前实例,完全不需要手动传self进去。

你这行代码相当于把当前的Student实例当成clgName参数传给了父类,导致self.collegename实际上存储的是这个Student对象,而不是默认的'KIIT'。当你打印的时候,Python尝试输出这个对象的字符串表示,终端可能因为长度限制截断显示成了'ra...'。

修正后的代码

只需要把super().__init__(self)改成super().__init__(),让父类使用默认的'KIIT'初始化collegename即可:

class College:
    def __init__(self, clgName='KIIT'):
        self.collegename = clgName
    def showname(self):
        return self.collegename

class Student(College):
    def __init__(self, studentName, studentRoll):
        super().__init__()  # 移除多余的self参数
        self.studentname = studentName
        self.studentroll = studentRoll
    def show(self):
        print(self.studentname, self.studentroll, self.collegename)

p = Student('ram', 22)
p.show()

运行结果

运行修正后的代码,就能得到你期望的输出:

ram 22 KIIT

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:59:20