0% found this document useful (0 votes)
10 views

Lecture 23

The document discusses inheritance and polymorphism in object-oriented programming. It provides an example of defining a base GeometricObject class and inheriting Circle and Rectangle subclasses that extend it, overriding methods and properties as needed.

Uploaded by

Maxi Brad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Lecture 23

The document discusses inheritance and polymorphism in object-oriented programming. It provides an example of defining a base GeometricObject class and inheriting Circle and Rectangle subclasses that extend it, overriding methods and properties as needed.

Uploaded by

Maxi Brad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Computer Science 1001

Lecture 23

Lecture Outline

• Inheritance and Polymorphism

– CS1001 Lecture 23 –
Example: revised Circle class
import math

class Circle:
def __init__(self, x = 0, y = 0, radius = 0):
self.__x = x
self.__y = y
self.__radius = radius

def getX(self):
return self.__x

def getY(self):
return self.__y

def getRadius(self):
return self.__radius

def setX(self, x):


self.__x = x

def setY(self, y):


self.__y = y

def setRadius(self, radius):


self.__radius = radius

def getPerimeter(self):
return 2 * self.__radius * math.pi

def getArea(self):

– CS1001 Lecture 23 – 1
return self.__radius * self.__radius * math.pi

def containsPoint(self, x, y):


d = distance(x, y, self.__x, self.__y)
return d <= self.__radius

def contains(self, circle):


d = distance(self.__x, self.__y, circle.__x, circle.__y)
return d + circle.__radius <= self.__radius

def overlaps(self, circle):


return distance(self.__x, self.__y, circle.__x, circle.__y) \
<= self.__radius + circle.__radius

def __contains__(self, anotherCircle):


return self.contains(anotherCircle)

def __lt__(self, secondCircle):


return self.cmp(secondCircle) < 0

def __le__(self, secondCircle):


return self.cmp(secondCircle) <= 0

def __gt__(self, secondCircle):


return self.cmp(secondCircle) > 0

def __ge__(self, secondCircle):


return self.cmp(secondCircle) >= 0

# Compare two numbers


def cmp(self, secondCircle):
if self.__radius > secondCircle.__radius:

– CS1001 Lecture 23 – 2
return 1
elif self.__radius < secondCircle.__radius:
return -1
else:
return 0

def distance(x1, y1, x2, y2):


return math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2))

– CS1001 Lecture 23 – 3
Using the Circle class
x1 = float(input("Enter x1: "))
y1 = float(input("Enter y1: "))
radius1 = float(input("Enter radius1: "))
x2 = float(input("Enter x2: "))
y2 = float(input("Enter y2: "))
radius2 = float(input("Enter radius2: "))
c1 = Circle(x1, y1, radius1)
c2 = Circle(x2, y2, radius2)
print("Area for c1 is", c1.getArea())
print("Perimeter for c1 is", c1.getPerimeter())
print("Area for c2 is", c2.getArea())
print("Perimeter for c2 is", c2.getPerimeter())
print("c1 contains the center of c2?",
c1.containsPoint(c2.getX(), c2.getY()))
print("c1 contains c2?", c1.contains(c2))
print("c2 in c1?", c2 in c1)
print("c1 overlaps c2?", c1.overlaps(c2))
print("c1 < c2?", c1 < c2)

Sample output:
Enter x1: 3
Enter y1: 5
Enter radius1: 2
Enter x2: 8
Enter y2: 7
Enter radius2: 3
Area for c1 is 12.566370614359172
Perimeter for c1 is 12.566370614359172

– CS1001 Lecture 23 – 4
Area for c2 is 28.274333882308138
Perimeter for c2 is 18.84955592153876
c1 contains the center of c2? False
c1 contains c2? False
c2 in c1? False
c1 overlaps c2? False
c1 < c2? True

– CS1001 Lecture 23 – 5
Inheritance

• Object-oriented programming languages allow us to


define new classes from existing classes.

• This is called inheritance.

• We are defining subclasses from superclasses.

• Subclasses extend superclasses.

• Superclasses are also known as base classes or parent


classes.

• Subclasses are also known as derived classes or child


classes.

– CS1001 Lecture 23 – 6
Inheritance

• Inheritance allows us to:


– Reuse software
– Avoid redundancy
– Facilitate maintenance
– Represent relationships between classes

• A superclass should have properties and behaviours


that are common to other different classes.

• A subclass inherits all accessible data fields and


methods from its superclasses and adds other data
fields and methods.

• Consider the concept of a geometric shape.

• There are many types of shapes, but all shapes have


some common properties, for example, color.

– CS1001 Lecture 23 – 7
Inheritance example

GeometricObject
- color: str the color of the object (def: green)
- filled: bool filled or not filled (def: True)
GeometricObject(color: Construct a GeometricObject
str, filled: bool) with specified color and fill

getColor(): str return the color


setColor(color: str): None set the color
isFilled(): bool return the filled attribute
setFilled(filled: bool): None set the filled attribute
__str__(): str return a string representation

Rectangle
Circle - : float
- radius: float -  float
Circle(radius: float, color: R    :  
str, filled: bool) float, color: str :  , 

getRadius(): float g : float


setRadius(radius: float): None sg  float): None
getArea(): float   float
getPerimeter(): float s  float): None
getDiameter(): float getArea(): float
printCircle(): None getPerimeter(): float

– CS1001 Lecture 23 – 8
Example: geometric objects

We could define a GeometricObject as:


class GeometricObject:
def __init__(self, color="green", filled=True):
self.__color = color
self.__filled = filled

def getColor(self):
return self.__color

def setColor(self, color):


self.__color = color

def isFilled(self):
return self.__filled

def setFilled(self, filled):


self.__filled = filled

def __str__(self):
return "color: " + self.__color + \
" and filled: " + str(self.__filled)

– CS1001 Lecture 23 – 9
Defining inheritance

• To define a subclass we include the name of the


superclass as in:

class subClassName(superClassName):

• For example,

class Circle(GeometricObject):

• To refer to the superclass inside a subclass, use


super().

• For example, to invoke the __init__() method


of the superclass within the subclass, use
super().__init__().

– CS1001 Lecture 23 – 10
Example: geometric objects

We could then define specific types of shapes (for


example, Circle) that derive from GeometricObject:
class Circle(GeometricObject):
def __init__(self, radius, color="red", filled=True):
super().__init__(color,filled)
self.__radius = radius

def getRadius(self):
return self.__radius

def setRadius(self, radius):


self.__radius = radius

def getArea(self):
return math.pi*self.__radius**2

def getDiameter(self):
return 2*self.__radius

def getPerimeter(self):
return 2*math.pi*self.__radius

def printCircle(self):
print(self.__str__() + " radius: " + str(self.__radius))

– CS1001 Lecture 23 – 11
Example: geometric objects

We could also define a Rectangle as:


class Rectangle(GeometricObject):
def __init__(self, width=1, height=1, color="blue", filled=True):
super().__init__(color,filled)
self.__width = width
self.__height = height

def getWidth(self):
return self.__width

def getHeight(self):
return self.__height

def setWidth(self,width):
self.__width = width

def setHeight(self,height):
self.__height = height

def getArea(self):
return self.__width*self.__height

def getPerimeter(self):
return 2*(self.__width+self.__height)

– CS1001 Lecture 23 – 12
Example: geometric objects

• Circle and Rectangle inherit all of the methods


in GeometricObject.

• We need to call super().__init__() to create


the data fields defined in the superclass.

• Note that super().__color cannot be accessed


directly. We call super().setColor() to set the
color attribute.

• Calling self.__str__() within printCircle()


invokes the __str__() method in GeometricObject.

• Circle extends the GeometricObject class with a new


data field radius and several instance methods.

– CS1001 Lecture 23 – 13
Example: geometric objects

circle = Circle(1.5)
print("A circle", circle)
print("The radius is", circle.getRadius())
print("The area is", circle.getArea())
print("The diameter is", circle.getDiameter())
print("The color is", circle.getColor())
print("The circle is"," not" if not circle.isFilled() else "",
" filled",sep="")
circle.printCircle()

rectangle = Rectangle(2,4,filled=False)
print("\nA rectangle", rectangle)
print("The area is", rectangle.getArea())
print("The perimeter is", rectangle.getPerimeter())
print("The color is", rectangle.getColor())
print("The rectangle is"," not" if not rectangle.isFilled() else "",
" filled",sep="")

Output:
A circle color: red and filled: True
The radius is 1.5
The area is 7.0685834705770345
The diameter is 3.0
The color is red
The circle is filled
color: red and filled: True radius: 1.5

– CS1001 Lecture 23 – 14
A rectangle color: blue and filled: False
The area is 8
The perimeter is 12
The color is blue
The rectangle is not filled

– CS1001 Lecture 23 – 15

You might also like