Python继承中的O/P错误?

2024-05-16 22:33:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在练习Python继承并编写了这段代码

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,但它显示ram 22 <__main__.Student object at 0x00000238972C2CC0>

那么我做错了什么?如何打印所需的o/p? 请引导我,提前谢谢

@Daniel Roseman感谢先生澄清了我的疑问,所以如果我想通过这种方式得到同样的结果,那么我必须做的是,它的显示不需要位置论证

 class College:

    def __init__(self,clgName):
        self.collegename = clgName
    def showname(self):
        return(self.collegename)

class Student(College):
    def __init__(self,studentName,studentRoll):
        super().__init__()
        self.studentname = studentName
        self.studentroll = studentRoll
    def show(self):
        print(self.studentname,self.studentroll,self.collegename)


c=College('KIIT')
c.showname()
p = Student('ram',22)
p.show()

Tags: selfinitdefshowstudentclassramcollege
1条回答
网友
1楼 · 发布于 2024-05-16 22:33:37

您显式地将self传递给超级__init__调用;这将取代clgname参数。您不需要在那里传递它,这就像调用任何其他方法一样,因此self是隐式传递的

class Student(College):
    def __init__(self,studentName,studentRoll):
        super().__init__()
        ...

相关问题 更多 >