0% found this document useful (0 votes)
22 views105 pages

Chapter 10

Chapter 10 focuses on inheritance in object-oriented programming, explaining the relationship between superclasses and subclasses, and how subclasses can inherit and override methods. It covers key concepts such as inheritance hierarchies, the substitution principle, and polymorphism, along with practical examples like a geometric shape hierarchy and quiz question types. The chapter emphasizes the importance of correctly implementing subclass constructors and method overriding while avoiding common errors.

Uploaded by

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

Chapter 10

Chapter 10 focuses on inheritance in object-oriented programming, explaining the relationship between superclasses and subclasses, and how subclasses can inherit and override methods. It covers key concepts such as inheritance hierarchies, the substitution principle, and polymorphism, along with practical examples like a geometric shape hierarchy and quiz question types. The chapter emphasizes the importance of correctly implementing subclass constructors and method overriding while avoiding common errors.

Uploaded by

menumina7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Chapter 10

INHERITANCE
Chapter Goals
• To learn about inheritance
• To implement subclasses that inherit and override superclass
methods
• To understand the concept of polymorphism

4/15/2025 1
In this chapter, you will learn how the notion of inheritance
expresses the relationship between specialized and general
classes.

Contents
• Inheritance Hierarchies
• Implementing Subclasses
• Calling the Superclass constructor
• Overriding Methods
• Polymorphism
• Application: A geometric shape hierarchy

4/15/2025 2
Inheritance Hierarchies
• In object-oriented programming, inheritance is a
relationship between:
• A superclass: a more generalized class
• A subclass: a more specialized class
• The subclass ‘inherits’ data (variables) and
behavior (methods) from the superclass

4/15/2025 3
A Vehicle Class Hierarchy

4/15/2025 4
• General

• Specialized

• More Specific

4/15/2025 5
The Substitution Principle

• Since the subclass Car “is-a” Vehicle


• Car shares common traits with Vehicle
• You can substitute a Car object in an
algorithm that expects a Vehicle object

The myCar = Car(. . .)


‘is- processVehicle(myCar) a’ is-a
relationship is represented by an arrow in a class
diagram and means
that the subclass can behave as an object of the
superclass.

4/15/2025 6
Quiz Question Hierarchy
• There are different types of quiz questions:
1)Fill-in-the-blank
2)Single answer choice The ‘root’ of the hierarchy is 3)
Multiple answer choice shown at the top.
4) Numeric answer 5) Free Response

• A question can:

4/15/2025 7
[Link]
• Display its text
• Check for correct
answer

4/15/2025 8
The classQuestion is the
‘ root’ of the hierarchy, also
known as thesuperclass

• Only handles Strings


• No support for:
• Numeric answers
• Multiple answer choice

4/15/2025 9
[Link] Creates an object
of the Question
class and uses

methods.

Programming Tip
• Use a Single Class for Variation in Values, Inheritance for Variation
in
Behavior
• If two vehicles only vary by fuel efficiency, use an instance
variable for the variation, not inheritance

4/15/2025 10
# Car instance variable
milesPerGallon

• If two vehicles behave differently, use


inheritance

Be careful not to over-use inheritance

4/15/2025 11
The Cosmic Superclass: object
• In Python, every class that is declared without an explicit superclass
automatically extends the class object

4/15/2025 12
Implementing Subclasses

• Consider implementing ChoiceQuestion to handle:

• How does ChoiceQuestion differ from Question?


• It stores choices (1,2,3 and 4) in addition to the question
• There must be a method for adding multiple choices
• The display() method will show these choices below the question,
numbered appropriately

4/15/2025 13
In this section you will see how to form a subclass and how a
subclass automatically inherits from its superclass
Inheriting from the Superclass
• Subclasses inherit from the superclass:
• All methods that it does not override
• All instance variables
• The Subclass can
• Add new instance variables
• Add new methods
• Change the implementation of inherited methods

4/15/2025 14
Form a subclass by
specifying what is
different from the
superclass.

Overriding Superclass Methods


• Can you re-use any methods of the Question class? • Inherited methods
perform exactly the same
• If you need to change how a method works:
• Write a new more specialized method in the subclass
• Use the same method name as the superclass method you want to replace
• It must take all of the same parameters
• This will override the superclass method

4/15/2025 15
• The new method will be invoked with the same method name
when it is called on a subclass object

A subclass can override a method


of the superclass by providing a
new implementation.

4/15/2025 16
Planning the Subclass
• Pass the name of the superclass Question as part of the definition of the
subclass

class ChoiceQuestion(
Question):
# The subclass has its own constructor.
def _ _init_ _(self) :
. . .
# This instance variable is added to the subclass.
self._choices = []

# This method is added


to the subclass
def addChoice(self, choice, correct) :
. . .
# This method overrides
a method from the superclass
def void display(self) :
. . .
4/15/2025 17
• Inherits text and answer variables
• Add new instance variable choices

4/15/2025 18
Syntax 10.1: Subclass Definition
• The class name inside parentheses in the class header denotes inheritance.

4/15/2025 19
Implementing AddChoice()
• The method will receive three parameters
• As usual for a class method the self parameter is required
4/15/2025 20
• The text for the choice
• A Boolean denoting if it is the correct choice or not
• It appends the text as a _choice, sets choice number to the _answer and

calls the inherited setAnswer() method: def addChoice(self,

choice, correct) :

self._choices.append(choice
) if correct :
# Convert the length of the list to a string.
choiceString = str(len(self._choices))
[Link](choiceString)

4/15/2025 21
Common Error 10.1 (1)
• Confusing Super- and Subclasses
• If you compare an object of type ChoiceQuestion with an object of type
Question, you find that:
• the ChoiceQuestion object is larger; it has an added instance variable,
_choices,
• the ChoiceQuestion object is more capable; it has an addChoice()
method.

4/15/2025 22
Common Error 10.1 (2)
• So why is ChoiceQuestion called the subclass and Question the
superclass?
• The super/sub terminology comes from set theory.
• Look at the set of all questions.
• Not all of them are ChoiceQuestion objects; some of them are other kinds
of questions.
• The more specialized objects in the subset have a richer state and more
capabilities.

4/15/2025 23
10.3 Calling the Superclass Constructor (1)
• A subclass constructor can only define the instance variables of the subclass.
• But the superclass instance variables also need to be defined.
• The superclass is responsible for defining its own instance variables.
• Because this is done within its constructor, the constructor of the subclass
must explicitly call the superclass constructor.

4/15/2025 24
10.3 Calling the Superclass Constructor (2)

To distinguish between super- and sub- class constructor use the
super() function in place of the self reference when calling
the constructor: class ChoiceQuestion(Question) :
def _ _init_ _(self) :
super()._ _init_ _()
self._choices = []

4/15/2025 25
• The superclass constructor should be called before the subclass defines
its own instance variables.
10.3 Calling the Superclass Constructor (3)

• If a superclass constructor requires arguments, you must provide those


arguments to the _ _init_ _() method.

class ChoiceQuestion(Question) :
def _ _init_ _(self, questionText) :

4/15/2025 26
super()._ _init_ _(questionText)
self._choices = []

4/15/2025 27
Syntax 10.2: Subclass Constructor

4/15/2025 28
4/15/2025 29

Example: Superclass Constructor (1)

• Suppose we have defined a Vehicle class and the constructor


which requires an argument:

class Vehicle :
def _ _init_ _(self,
numberOfTires) :

class Car(Vehicle) :
def _ _init_ _(self) : # 1

4/15/2025 30
self._numberOfTires =
numberOfTires . . .

• We can extend the Vehicle class by defining a Car subclass:

4/15/2025 31

Example: Superclass Constructor (2)

# Call the superclass constructor to define its


# instance
super()._ _init_ _(4)
variable. #
2
# This instance variable is added by
#
the
self._plateNumber = "??????"
subclass. #
3

4/15/2025 32
Now as the subclass is defined, the parts of the object are added as
attributes to the object:

4/15/2025 33

10.4 Overriding Methods


• The ChoiceQuestion class needs a display() method that
overrides the display() method of the Question class • They are
two different method implementations
• The two methods named display are:
• Question display()
• Displays the text of the private attribute of class Question
• ChoiceQuestion display()
• Overrides Question display method
• Displays the instance variable text String

4/15/2025 34
• Displays the list of choices which is an attribute of ChoiceQuestion

4/15/2025 35
Tasks Needed for Display()

:1
Display the question text.
• Display the answer choices.

• The second part is easy because the answer choices are an instance
variable of the subclass.

4/15/2025 36
Tasks Needed for Display()

class ChoiceQuestion(Question) :
. . .
def display(self) :
# Display the question text.
. . .
# Display the answer choices.
for i in range(len(self._choices()) :
choiceNumber = i + 1
print("%d: %s" % (choiceNumber,
self._choices[i]))

:2
Display the question text.

4/15/2025 37
Tasks Needed for Display()

• Display the answer choices.

• The first part is trickier!


• You can’t access the textvariable of the superclass directly
because it is private.
• Call the display() method of the superclass, using the
super() function:

def display(self) :
# Display the question text.
super().display()# OK
# Display the answer choices.

4/15/2025 38
Tasks Needed for Display()

:3
Display the question text.
• Display the answer choices.

• The first part is trickier! (Continued)


• If you use the selfreference instead of the super()
function, then the method will not work as intended.

4/15/2025 39
Tasks Needed for Display()

def display(self) :
# Display the question text.
[Link]()
# Error—invokes display() of ChoiceQuestion
.
. . .

4/15/2025 40
[Link] (1)

4/15/2025 41
Creates two objects of the
ChoiceQuestionclass, uses
new addChoice()method.

Calls presentQuestion()
- next
page

4/15/2025 42
[Link] (2)

Uses ChoiceQuestion
(subclass) display()
method.

[Link] (1)

4/15/2025 43
Inherits from Questionclass.

New addChoice()
method.

[Link] (2)
4/15/2025 44
Overridden display()
method.

4/15/2025 45
Common Error 10.2 (1)
• Extending the functionality of a superclass method but forgetting to call the
super() method.
• For example, to compute the salary of a manager, get the salary of the
underlying Employee object and add a bonus:

class Manager(Employee) :
. . .
def getSalary(self) :
base =[Link]
()
# Error: should be super().getSalary()
return base + self._bonus

• Here self refers to an object of type Manager and there is a


getSalary() method in the Manager class.

4/15/2025 46
Common Error 10.2 (2)
• Whenever you call a superclass method from a subclass method with the same
name, be sure to use the super() function in place of the self reference.

class Manager(Employee) :
. . .
def getSalary(self) :
base = super().getSalary()
return base + self._bonus

10.5 Polymorphism
• QuestionDemo2 passed two ChoiceQuestion objects to the
presentQuestion() method

4/15/2025 47
• Can we write a presentQuestion() method that displays both
Question and ChoiceQuestion types?
• With inheritance, this goal is very easy to realize!
• In order to present a question to the user, we need not know the exact type of
the question.
• We just display the question and check whether the user supplied the correct
answer.

def presentQuestion(q) :
[Link]()
response = input("Your answer: ")
print([Link](
response))

Which Display() method was called?

4/15/2025 48
• presentQuestion() simply calls the display() method of whatever
type is passed:
def presentQuestion(q) :
[Link]()
. . .
 If passed an object of the Questionclass:
 Question display()
 If passed an object of the ChoiceQuestion class:
 ChoiceQuestion display()

• The variable q does not know the type of object to which it refers:

_
_

display()

4/15/2025 49
Why Does This Work?
• As discussed in Section 10.1, we can substitute a subclass object whenever a
superclass object is expected:

second = ChoiceQuestion()
presentQuestion(second) # OK to pass a
ChoiceQuestion

• Note however you cannot substitute a superclass object when a subclass object
is expected.
• An AttributeError exception will be raised.
• The parent class has fewer capabilities than the child class (you cannot invoke a
method on an object that has not been defined by that object’s class).

4/15/2025 50
Polymorphism Benefits

4/15/2025 51
• In Python, method calls are always determined by the type of the actual
object, not the type of the variable containing the object reference

4/15/2025 52
• This is called dynamic method lookup
• Dynamic method lookup allows us to treat objects of different classes in a
uniform way

4/15/2025 53
• This feature is called polymorphism
• We ask multiple objects to carry out a task, and each object does so in its
own way

4/15/2025 54
• Polymorphism makes programs easily extensible

4/15/2025 55
Creates an object of
the Questionclass

Creates an object of theChoiceQuestion


class, uses newaddChoice() method.

Calls presentQuestion() - next


page - passed both types of objects.

4/15/2025 56
[Link] (1)

4/15/2025 57
[Link] (2)
Receives a parameter of Uses
the super-class type appropriate
display
method.

4/15/2025 58
Special Topic 10.2
• Subclasses and Instances:
• You learned that the isinstance() function can be used to
determine if an object is an instance of a specific class.
• But the isinstance() function can also be used to determine
if an object is an instance of a subclass.
• For example, the function call:
isinstance(q, Question)
• will return True if q is an instance of the Question class or of any
subclass that extends the Question class,
• otherwise, it returns False.

4/15/2025 59
Use of Isinstance()

A common use of the isinstance() function


is to verify that the arguments passed to a
function or method are of the correct type.
def
if not isintance(q,
presentQuestion(q) :
raise TypeError("The
Question) : argument is not a Question
or one of its
subclasses.")

4/15/2025 60
Special Topic 10.3
• Dynamic Method Lookup
• Suppose we move the presentQuestion() method to inside the
Question class and call it as follows:

4/15/2025 61
cq =
[Link]("In which country was the inventor of Python
ChoiceQuestion()
. .
born?")
[Link](
.
)
def
selfdisplay(
presentQuestion(self) :
response
. ) = "Your answer:
) "
print(self
input( checkAnswe
(respons )
. r e )

• Which display() and checkAnswer() methods will be called?

4/15/2025 62
Dynamic Method Lookup
• If you look at the code of the presentQuestion()
method, you can see that these methods are executed on the
self reference parameter.
• Because of dynamic method lookup, the ChoiceQuestion versions of
the display() and checkAnswer() methods are called
automatically.
• This happens even though the presentQuestion() method is declared
in the Question class, which has no knowledge of the
ChoiceQuestion class.

4/15/2025 63
class Question :
def presentQuestion(self) :
[Link]()
response = input("Your answer: ")
print([Link]
(response))

Special Topic 10.4


• Abstract Classes and methods
• If it is desirable to force subclasses to override a method of a base class,
you can declare a method as abstract.
• You cannot instantiate an object that has abstract methods
• Therefore the class is considered abstract (it has 1+ abstract methods)
• It’s a tool to force programmers to create subclasses (avoids the trouble of coming
up with useless default methods that others might inherit by accident).

4/15/2025 64
• In Python, there is no explicit way to specify that a method is an abstract
method. Instead, the common practice among Python programmers is to
have the method raise a NotImplementedError exception as its only
statement:

class Account :
. . .
def deductFees(self) :
raise NotImplementedError

Common Error 10.3


• Don’t Use Type Tests
• Some programmers use specific type tests in order to implement behavior
that varies with each class:
4/15/2025 65
if isinstance(q, ChoiceQuestion) : # Don’t do this.
# Do the task the ChoiceQuestion way.
elif isinstance(q, Question) :
# Do the task the Question way.

• This is a poor strategy.


• If a new class such as NumericQuestion is added, then you need to
revise all parts of your program that make a type test, adding another
case:

elif isinstance(q, NumericQuestion) :


# Do the task the NumericQuestion way.

4/15/2025 66
Alternate to Type Tests
• Polymorphism
• Whenever you find yourself trying to use type tests in a hierarchy of
classes, reconsider and use polymorphism instead.
• Declare a method doTheTask() in the superclass, override it in the
subclasses, and call

[Link]()

Steps to Using Inheritance

4/15/2025 67
• As an example, we will consider a bank that offers customers the
following account types:
1) A savings account that earns interest. The interest compounds monthly and
is based on the minimum monthly balance.
2) A checking account that has no interest, gives you three free withdrawals
per month, and charges a $1 transaction fee for each additional withdrawal.
• The program will manage a set of accounts of both types
• It should be structured so that other account types can be added without
affecting the main processing loop.
• The menu: D)eposit W)ithdraw M)onth end Q)uit
• For deposits and withdrawals, query the account number and amount. Print the
balance of the account after each transaction.
• In the “Month end” command, accumulate interest or clear the transaction
counter, depending on the type of the bank account. Then print the balance of
all accounts.

4/15/2025 68
Steps to Using Inheritance
1) List the classes that are part of the hierarchy.
SavingsAccount
CheckingAccount

2) Organize the classes into an inheritance. hierarchy


Base on superclass BankAccount

3) Determine the common


responsibilities.

4/15/2025 69
a. Write Pseudocode for each task
b. Find common tasks
Using Inheritance: Pseudocode

4/15/2025 70
Steps to Using Inheritance

4/15/2025 71
4) Decide which methods are overridden in subclasses.
• For each subclass and each of the common responsibilities, decide whether the
behavior can be inherited or whether it needs to be overridden 5) Declare
the public interface of each subclass.
• Typically, subclasses have responsibilities other than those of the superclass.
List those, as well as the methods that need to be overridden.
• You also need to specify how the objects of the subclasses should be
constructed.
6) Identify instance variables.
• List the instance variables for each class. Place instance variables that are
common to all classes in the base of the hierarchy.
7) Implement constructors and methods.
8) Construct objects of different subclasses and process them.

4/15/2025 72
10.6 Application
• Creating a geometric shape class hierarchy
• To create complex scenes beyond the simple graphics introduced in
Chapter 2, you may need a large number of shapes that vary in
color, size, or location.
• Rather than calling the various methods again and again, it would be
useful to have classes that model the various geometric shapes.
• Using shape classes, a programmer can create a shape object with
specific characteristics, then use the same object to draw multiple
instances of the shape with only minor changes.
Inheritance Diagram of Geometric Shapes

4/15/2025 73
4/15/2025 74
The Base Class
• The GeometricShape class should provide the functionality that
is common among the various subclasses:
• Setting the colors used to draw the shape.
• Getting and setting the coordinates for the upper-left corner of a
bounding box.
• Computing the width and height of the shape (or the bounding box
used to define the shape).
• Drawing the shape on a canvas.
• Due to the amount of variation between shapes all subclasses will
have to override the draw() method.

4/15/2025 75
Attributes of the Base Class
• The instance variables _fill and _outline can store the fill
and outline colors used by the shapes.
• Coordinates of the top left hand corner of the bounding box for the
shape can be stored in the instance variables _x and _y

4/15/2025 76
Setting the Attributes
• The constructor of the GeometricShape base class needs to define
the common instance variables.

class GeometricShape :
## Construct a basic geometric shape.
# @param x thex-coordinate of the shape
# @param y they-coordinate of the shape
def _ _init_ _(self, x, y) :
self._x = x
self._y = y
self._fill = None
self._outline = "black"

4/15/2025 77
Accessor Methods
• As expected they will return the values stored in the instance
variables.
def getX(self) :
return self._x

def getY(self) :
return self._y

def getWidth(self) :
return 0

def getHeight(self) :
return 0
4/15/2025 78
• Because the getWidth() and getHeight() methods return
zero they should be overridden by subclasses.

Mutator Methods
• We define three mutator methods for setting the colors.
• Two methods set the outline or fill color individually, and the third
method sets both to the same color:

4/15/2025 79
def setFill(self, color = None) :
self._fill = color

def setOutline(self, color = None) :


self._outline = color

def setColor(self, color) :


self._fill = color
self._outline = color

Other Methods

4/15/2025 80
• The move() method moves the shape by a given amount (x, y)
coordinates.
def moveBy(self, dx, dy) :
self._x = self._x + dx
self._y = self._y + dy

• As indicated earlier, the draw() method has to be overridden for


each subclass’s specific shape but the common operation (setting the
drawing colors) is included here.

def draw(self, canvas) :


[Link](self._fill)
[Link](self._outline)

4/15/2025 81
The

Rectangle Class (1)


• The Rectangle class inherits from GeometricShape.
• The constructor passes the upper-left corner to the superclass and
stores the width and height.

def _ _init_ _(self, x, y, width, height) :


super()._ _init_ _(x, y)
self._width = width
self._height = height

4/15/2025 82
The

Rectangle Class (2)


• The draw method is overridden in the Rectangle subclass to include
the call to the appropriate canvas method.

def draw(self, canvas) :


• Accessors are overridden (from the ones that return
zero).super().draw(canvas) # Parent method sets
colors
[Link]([Link](), [Link](),
self._width, self._height)

4/15/2025 83
The
def getWidth(self) :
return self._width

def getHeight(self) :
return self._height

Line Class (1)


• A line is specified by its start and end points.

4/15/2025 84
The

• It is possible that neither of these points is the upper-left corner of the


bounding box.
• Instead, we need to compute the smaller of the x- and y-coordinates
and pass those values to the superclass constructor.

4/15/2025 85
The

Line Class (2)


• We also need to store the start and end points in instance variables
because we need them to draw the line.

def _ _init_ _(self, x1, y1, x2, y2) :


super()._ _init_ _(min(x1, x2), min(y1, y2))
self._startX = x1
self._startY = y1
self._endX = x2
self._endY = y2

4/15/2025 86
Line Class: Methods (1)
• The width and height are the differences between the starting and
ending x- and y-coordinates.
• However, if the line isn’t sloping downward, we need to take the
absolute values of the difference.

def getWidth(self) :
return abs(self._endX
- self._startX)

def getHeight(self) :
return abs(self._endY
- self._startY)

4/15/2025 87
Line Class: Methods (2)
• As noted the draw() method must be overridden def
draw(self, canvas) :
super().draw(canvas)
[Link](self._startX, self._startY,
self._endX, self._endY)

• Also the moveBy() method must be overridden so that it


adjusts the starting and ending points, in addition to the top-
left corner.

def moveBy(self, dx, dy) :

4/15/2025 88
super().moveBy(dx, dy)
self._startX = self._startX +
dx self._startY = self._startY
+ dy self._endX = self._endX +
dx self._endY = self._endY + dy

Wrapper Class: Square


• A wrapper class wraps or encapsulates the functionality of another
class to provide a more convenient interface.
• For example, we could draw a square using the Rectangle
subclass.
• But it requires that we supply both the width and height.

4/15/2025 89
• Because a square is a special case of a rectangle, we can define a
Square subclass that extends, or wraps, the Rectangle class and only
requires one value, the length of a side.

class Square(Rectangle) :
def _ _init_ _(self, x, y, size) :
super()._ _init_ _(x, y, size,
size)

4/15/2025 90
4/15/2025 91
[Link]

4/15/2025 92
Groups of Shapes
• The Group subclass does not actually draw a geometric shape.
• Instead it can be used to group basic geometric shapes to create a complex
shape.
• For example, suppose you construct a door using a rectangle, a circle for
the doorknob, and a circle for the peep hole.
• The three components can be stored in a Group in which the individual
shapes are defined relative to the position of the group.
• This allows the entire group to be moved to a different position without
having to move each individual shape.

4/15/2025 93
The Group Class
• To create a Group, you provide the coordinates of the upper-left corner
of its bounding box.
• The class defines an instance variable that stores the shapes in a list.
• As new shapes are added to a Group object, the width and height of
the bounding box expands to enclose the new shapes.

4/15/2025 94
4/15/2025 95
Group
Class Methods (1)
• Create the group with its bounding box positioned at (x, y).

def _ _init_ _(self, x = 0, y = 0) :


super()._ _init_ _(x, y)
self._shapeList = []

• Adding a shape to the group involves several steps.


• First, the shape has to be appended to the list:

def add(self, shape) :


self._shapeList.append(shape)

4/15/2025 96
Group
Class Methods (2)
• The individual shapes are positioned relative to the upper-left
corner of the group’s bounding box.
• We must ensure that each shape is positioned below and to the
right of this point. If it is not, it must be moved.

# Keep the shape within top and left edges of the


# bounding box.
if [Link]() < 0 : [Link](-
[Link](), 0)
if [Link]() < 0 :
[Link](0, -[Link]())

4/15/2025 97
Group
Class Methods (3)
• The width of the group is determined by the rightmost extent of any
of the group’s members.
• The rightmost extent of a shape is [Link]() +
[Link](). The following method computes the
maximum of these extents.
def getWidth(self) :
width = 0
for shape in self._shapeList :
width = max(width, [Link]() +
[Link]())
return width

4/15/2025 98
Group
Class Methods (4)
• The height of the group (the bottommost extent) is computed in the
same way as the width.
def getHeight(self) :
height = 0
for shape in self._shapeList :
height = max(height, [Link]() +
[Link]())
return height

Class Methods (5)


• The entire group can be drawn on the canvas.

4/15/2025 99
Group
• The shapes contained in the group are defined relative to the
upperleft corner of its bounding box.
• Before a shape can be drawn, it has to be moved to its position
relative to the upper-left corner of the group’s bounding box.

def draw(self, canvas) :


for shape in self._shapeList :
[Link]([Link](), [Link]())
[Link](canvas)
[Link](
-[Link](),-[Link]())

4/15/2025 100
Summary: Inheritance

• A subclass inherits data and behavior from a superclass.


• You can always use a subclass object in place of a superclass object.
• A subclass inherits all methods that it does not override.
• A subclass can override a superclass method by providing a new
implementation.
• In Python a class name inside parentheses in the class header indicates that a
class inherits from a superclass.

4/15/2025 101
Summary: Overriding Methods

• An overriding method can extend or replace the functionality


of the superclass method.
• Use the reserved word super to call a superclass method.
• To call a superclass constructor, use the super reserved
word before the subclass defines its own instance variables.

4/15/2025 102
• The constructor of a subclass can pass arguments to a
superclass constructor, using the reserved word super.
Summary: Polymorphism

• A subclass reference can be used when a superclass reference is expected.


• Polymorphism (“having multiple shapes”) allows us to manipulate objects that
share a set of tasks, even though the tasks are executed in different ways.
• An abstract method is a method whose implementation is not specified.

4/15/2025 103
Summary: Use Inheritance for Designing a
Hierarchy of Shapes

• The GeometricShape class provides methods that are common to


all shapes.
• •Each subclass of GeometricShape must override the draw()
method.
• A shape class constructor must initialize the coordinates of its upperleft
corner.

4/15/2025 104
• Each shape subclass must override the methods for computing the
width and height.
• A Group contains shapes that are drawn and moved together.

4/15/2025 105

You might also like