0% found this document useful (0 votes)
20 views14 pages

Lecture 24

The document discusses inheritance and polymorphism in object-oriented programming. It describes how a superclass can be extended to create more specialized subclasses, and how subclasses can override methods from the superclass. It provides an example of creating question objects with inheritance, where a general Question class is extended to create a MultipleChoice subclass.

Uploaded by

Maxi Brad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views14 pages

Lecture 24

The document discusses inheritance and polymorphism in object-oriented programming. It describes how a superclass can be extended to create more specialized subclasses, and how subclasses can override methods from the superclass. It provides an example of creating question objects with inheritance, where a general Question class is extended to create a MultipleChoice subclass.

Uploaded by

Maxi Brad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Computer Science 1001

Lecture 24

Lecture Outline

• Inheritance and Polymorphism

– CS1001 Lecture 24 –
Inheritance

• Inheritance enables us to define a general class


(superclass) and later extend it to more specialized
classes (subclasses).

• Note that a subclass is not a subset of its superclass.


In fact, a subclass usually contains more information
and methods than its superclass.

• Inheritance models the “is-a” relationship. For


example, a rectangle “is-a” geometric object.

• Not all “is-a” relationships should be modelled using


inheritance.

• For example, although a square “is-a” rectangle, it


is best to represent a square as its own geometric
object since separate width and height properties do
not make sense for a square (a single side attribute
would be best).

– CS1001 Lecture 24 – 1
Overriding methods

• Sometimes a subclass needs to modify the


implementation of a method defined in the
superclass.

• This is referred to as method overriding.

• To override a method, the method must be defined


in the subclass using the same header as in its
superclass.

• For example, the __str__() method in


GeometricObject returns a string describing the
color and fill; we may want to include information
more specific to a given shape (ex. radius of a
Circle).

• In class Circle we could have:

def __str__(self):
return super().__str__() + "radius: " + str(self.__radius)

– CS1001 Lecture 24 – 2
Overriding methods

• Both __str__ methods, the one in the


GeometricObject class and the one in the Circle
class, can be used in the Circle class.

• To invoke the __str__ method in the


GeometricObject class from within Circle, we
use super().__str__().

• We could also override __str__() for a Rectangle:

def __str__(self):
return super().__str__() + "width: " + str(self.__width) \
+ "height: " + str(self.__height)

• Note that a private method cannot be overridden.

• If a method defined in a subclass has the same


name as a private method in its superclass, the two
methods are unrelated.

– CS1001 Lecture 24 – 3
The object class

• Every class in Python is descended from the object


class.

• The object class is defined in the Python library.

• If no inheritance is specified when a class is defined,


the superclass of the class is the object class.

• For example, class ClassName: is equivalent to


class ClassName(object).

• All methods in the object class can be used within


classes that we create.

• All methods in the object class are special


methods.

– CS1001 Lecture 24 – 4
The object class

• The following methods are contained in the object


class:

__new__() # invoked during object creation - calls __init__()


__init__() # invoked to initialize object
__str__() # returns string with class name and memory location
__eq__(other) # returns True if 2 objects are the same

• Typically we would override __init__() but not


__new__().

• It is often good to override __str__() to provide a


more informative description of the object.

• We have seen how to override __eq__() to compare


contents since by default x.__eq__(y) is False for
objects with different ids, even though the contents
of x and y may be equal.

– CS1001 Lecture 24 – 5
Example: questions

• Suppose that we want to create a series of questions


and answers.

• A question can be presented in many different forms.

• For example, we could have multiple choice


questions, or fill in the blank questions.

• The general concept of a question is the same in all


cases since all questions require text for the question
itself and a correct answer.

• Here, we will create a general Question class


which can form the superclass of several subclasses
representing different types of 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

• If we want a simple question where the user has to


type in an answer, then we can create an instance
of Question, as in:

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

• If we want a multiple-choice type question


we can create a subclass of Question named
MultipleChoice.

• Recall that a subclass will inherit the accessible


attributes and methods of its superclass.

• To implement the subclass we include only attributes


that are not a part of the superclass, and methods
that are either new (specific) to the subclass or
whose implementation needs to be changed from
the superclass inherited method (overridden).

• For a MultipleChoice class we must have a place


to store the various choices, a method to add the
choices, and a method to display the choices.

– 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

• We can now generate a series of questions with


different types:

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...

When was Python first released?


1. 1988
2. 1991
3. 1994
4. 1997
5. 2000
Enter your answer: 2
You are correct!

Python is a successor of which language?


1. C
2. Fortran
3. Java
4. ABC
5. Perl
Enter your answer: 4
You are correct!

– 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

You might also like