Professional Documents
Culture Documents
Lecture 24
Lecture 24
Lecture 24
Lecture 24
Lecture Outline
– CS1001 Lecture 24 –
Inheritance
– CS1001 Lecture 24 – 1
Overriding methods
def __str__(self):
return super().__str__() + "radius: " + str(self.__radius)
– CS1001 Lecture 24 – 2
Overriding methods
def __str__(self):
return super().__str__() + "width: " + str(self.__width) \
+ "height: " + str(self.__height)
– CS1001 Lecture 24 – 3
The object class
– CS1001 Lecture 24 – 4
The object class
– CS1001 Lecture 24 – 5
Example: questions
– CS1001 Lecture 24 – 6
Example: questions
class Question:
def __init__(self):
self.__text = ""
self.__answer = ""
def setText(self,questionText):
self.__text = questionText
def setAnswer(self,correctAnswer):
self.__answer = correctAnswer
def checkAnswer(self,response):
return response == self.__answer
def display(self):
print(self.__text)
– CS1001 Lecture 24 – 7
Example: questions
def main():
q = Question()
q.setText("Who is the inventor of Python?")
q.setAnswer("Guido van Rossum")
q.display()
tryAgain = "Y"
while tryAgain=="Y":
response = input("Enter your answer: ")
if q.checkAnswer(response):
print("You are correct!")
tryAgain=""
else:
tryAgain = input("Enter ’Y’ to try again: ")
if __name__=="__main__":
main()
– CS1001 Lecture 24 – 8
Example: questions
– CS1001 Lecture 24 – 9
Example: questions
class MultipleChoice(Question):
def __init__(self):
super().__init__()
self.__choices = []
def addChoice(self,option,correct):
self.__choices.append(option)
if correct:
self.setAnswer(str(self.__choices.index(option)+1))
def display(self):
super().display() # display question
for i in range(len(self.__choices)): # display choices
print(i+1,". ",self.__choices[i],sep="")
– CS1001 Lecture 24 – 10
Example: questions
def main():
q = Question()
q.setText("Who is the inventor of Python?")
q.setAnswer("Guido van Rossum")
q1=MultipleChoice()
q1.setText("When was Python first released?")
q1.addChoice("1988",False)
q1.addChoice("1991",True)
q1.addChoice("1994",False)
q1.addChoice("1997",False)
q1.addChoice("2000",False)
q2=MultipleChoice()
q2.setText("Python is a successor of which language?")
q2.addChoice("C",False)
q2.addChoice("Fortran",False)
q2.addChoice("Java",False)
q2.addChoice("ABC",True)
q2.addChoice("Perl",False)
showQuestion(q)
showQuestion(q1)
showQuestion(q2)
– CS1001 Lecture 24 – 11
def showQuestion(q):
q.display() # display question
response = input("Enter your answer: ")
if q.checkAnswer(response):
print("You are correct!")
else:
print("This is incorrect...")
print()
• Sample input/output:
Who is the inventor of Python?
Enter your answer: Bill Gates
This is incorrect...
– CS1001 Lecture 24 – 12
• Note that when we called showQuestion we
passed in a Question on the first call but a
MultipleChoice on the second and third calls.
– CS1001 Lecture 24 – 13