0

I am trying to create a Class Person and inherit it to class Student with the following codes. When I try to run

class Person:
    def __init__(self, firstName, lastName, idNumber):
        self.firstName = firstName
        self.lastName = lastName
        self.idNumber = idNumber
    def printPerson(self):
        print "Name:", self.lastName + ",", self.firstName
        print "ID:", self.idNumber
class Student(Person):
    def __init__(self, firstName, lastName, idNumber, scores):
        super(Student, self).__init__(firstName, lastName, idNumber)
        self.scores = scores
    def calculate(self):
        if self.scores > 90:
            print('Honor Student')

And I do,

s = Student('Sam', 'Smith', 123456, 95)
s.calculate()

I was assuming it should print 'Honor Student' however it throws a typeError giving me following message TypeError: must be type, not classobj on super. What am I doing wrong here. I saw few post with similar problems but can't get to work on mine.

amicitas
  • 13,053
  • 5
  • 38
  • 50
user1430763
  • 37
  • 1
  • 8
  • Can you post the actual traceback? – jordanm Jun 18 '16 at 03:36
  • Traceback (most recent call last) 14 if self.scores > 90: 15 print('Honor Student') ---> 16 s = Student('Sam', 'Smith', 123456, 95) 17 s.calculate() in __init__(self, firstName, lastName, idNumber, scores) 9 class Student(Person): 10 def __init__(self, firstName, lastName, idNumber, scores): ---> 11 super(Student, self).__init__(firstName, lastName, idNumber) 12 self.scores = scores 13 def calculate(self): TypeError: must be type, not classobj – user1430763 Jun 18 '16 at 03:58

1 Answers1

2

The use of super only works for new-type classes.

All you need to do is to have Person inherit from object in the class definition.

class Person(object):
    def __init__(self, firstName, lastName, idNumber):
        self.firstName = firstName
        self.lastName = lastName
        self.idNumber = idNumber

    def printPerson(self):
        print "Name:", self.lastName + ",", self.firstName
        print "ID:", self.idNumber


class Student(Person):
    def __init__(self, firstName, lastName, idNumber, scores):
        super(Student, self).__init__(firstName, lastName, idNumber)
        self.scores = scores

    def calculate(self):
        if self.scores > 90:
            print('Honor Student')


Note that in Python 3 all classes are new-type, so the explicit inheritance from object is not necessary.

amicitas
  • 13,053
  • 5
  • 38
  • 50