Skip to content
Advertisement

How to print an instance of a parent class in base class?

I am able to print the name of Class Student when I inherit the class into Sports and define the values in the init method. but I am not able to figure out how to print the name given when Student class is created without defining the name in Sports class,

When I comment out the Student.__init__(self, 1, "name1", "addr1", 123456789, "std2@gmail.com", 1, 2021, "english") and define the values when the object is created, i want to print out these values.

class Student:
    def __init__(self, sid, name, addr, phno, mailid, sec, year, sub):
        self.sid = sid
        self.name = name
        self.addr = addr
        self.phno = phno
        self.mailid = mailid
        self.sec = sec
        self.year = year
        self.sub = sub

    def printStudent(self):
        print("name",self.name,"sid",self.sid,"sec",self.sec,"year",self.year,"sub",
              self.sub, "address",self.addr,"mailid",self.mailid,"phno",self.phno)


class Sports(Student):
    def __init__(self, nofsports, nofawards):
        Student.__init__(self, 1, "name1", "addr1", 123456789, "std2@gmail.com", 1, 2021,
                         "english")
        self.nofsports = nofsports
        self.nofawards = nofawards

    def printSports(self):
        print("name", self.name)


s1 = Student(2,"name2","addr2",1221232332,"std1@gmail.com",1,2020,"math")

s2 = Sports(2, 2)
s2.printSports()

When I comment out the Student.__init__(self, 1, "name1", "addr1", 123456789, "std2@gmail.com", 1, 2021, "english") and define the values when the object is created, I want to print out those values.

BTW, I am learning inheritance and new to python, and I could not understand why python is not able to print the instance of Student class as I have inherited it, maybe because it is not class attribute? Please let me know…

Advertisement

Answer

Normally a subclass __init__ method takes all the parameters of its superclass, plus any additional parameters the subclass needs. Then it can pass the common parameters to the superclass’s __init__ method.

class Sports(Student):
    def __init__(self, sid, name, addr, phno, mailid, sec, year, sub, nofsports, nofawards):
        super().__init__(sid, name, addr, phno, mailid, sec, year, sub)
        self.nofsports = nofsports
        self.nofawards = nofawards

    def printSports(self):
        print("name", self.name)

s2 = Sports(1, "name1", "addr1", 123456789, "std2@gmail.com", 1, 2021, "english", 2, 2)
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement