Python继承中的O / P错误?

时间:2018-05-04 08:28:53

标签: python inheritance

我正在练习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感谢先生清除我的怀疑,所以如果我希望通过这种方式获得相同的结果我必须做的事情,而不是它的显示super.__init__()需要一个位置参数

 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()

1 个答案:

答案 0 :(得分:4)

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

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