0% found this document useful (0 votes)
24 views24 pages

PP Module 4

Uploaded by

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

PP Module 4

Uploaded by

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

K S Institute of Technology

Department of Artificial Intelligence


and Machine Learning
Python Programming (18AI52)
Academic Year 2022-23 (Odd)
Semester/ Section : 5th A

By:
Dr. Vaneeta M
Associate Professor & Head
Dept. of AIML
KSIT

1
Overview of Syllabus
Module 4:
Classes and objects, Programmer-defined types, Attributes, Rectangles, Instances as return
values, Objects are mutable, Copying, Classes and functions, Time, Pure functions,
Modifiers, Prototyping versus planning, Classes and methods, Object-oriented features,
Printing objects, Another example, A more complicated example, Theinit method, The __str__
method, Operator overloading, Type-based dispatch, Polymorphism, Interface and
implementation, Inheritance, Card objects, Class attributes, Comparing cards, Decks,
Printing the deck, Add, remove, shuffle and sort, Inheritance, Class diagrams, Data
encapsulation
Textbook 2: Chapters 15 – 18

2
Chapter 15
Classes and objects

3
15.1 User-defined types
Python has many built-in data types.
For Example:
In mathematical notation, points are often written in parentheses with a comma separating the
coordinates.
For example, (0,0) represents the origin, and (x,y) represents the point x units to the right and
y units up from the origin.
There are several ways we might represent points in Python:
• We could store the coordinates separately in two variables, x and y.
• We could store the coordinates as elements in a list or tuple.
• We could create a new type to represent points as objects.

4
15.1 User-defined types
A user-defined type is also called a class. A class definition looks like this:
class Point(object):
"""represents a point in 2-D space""“
This header indicates that the new class is a Point, which is a kind of object, which is a built-
in
type.
Defining a class named Point creates a class object.
>>> print Point
<class '__main__.Point'>

5
15.1 User-defined types
• Because Point is defined at the top level, its “full name” is __main__.Point.
• The class object is like a factory for creating objects. To create a Point, you call Point as if
it were a function.
>>> blank = Point()
>>> print blank
<__main__.Point instance at 0xb7e9d3ac>
• The return value is a reference to a Point object, which we assign to blank. Creating a new
object is called instantiation, and the object is an instance of the class.
• When you print an instance, Python tells you what class it belongs to and where it is stored
in memory (the prefix 0x means that the following number is in hexadecimal).

6
15.2 Attributes
You can assign values to an instance using dot notation:
>>> blank.x = 3.0
>>> blank.y = 4.0
This syntax is similar to the syntax for selecting a variable from a module, such as math.pi or
string.whitespace. In this case, though, we are assigning values to named elements of an
object.
These elements are called attributes.
The following diagram shows the result of these assignments. A state diagram that shows an
object and its attributes is called an object diagram:

7
15.2 Attributes
The variable blank refers to a Point object, which contains two attributes. Each attribute refers
to a floating-point number.
You can read the value of an attribute using the same syntax:
>>> print blank.y
4.0
>>> x = blank.x
>>> print x
3.0
The expression blank.x means, “Go to the object blank refers to and get the value of x.” In this
case, we assign that value to a variable named x. There is no conflict between the variable x
and the attribute x.

8
15.2 Attributes
>>> print '(%g, %g)' % (blank.x, blank.y)
(3.0, 4.0)
>>> distance = math.sqrt(blank.x**2 + blank.y**2)
>>> print distance
5.0
You can pass an instance as an argument in the usual way. For example:
def print_point(p):
print '(%g, %g)' % (p.x, p.y)
print_point takes a point as an argument and displays it in mathematical notation. To invoke it,
you can pass blank as an argument:
>>> print_point(blank)
(3.0, 4.0)
Inside the function, p is an alias for blank, so if the function modifies p, blank changes.

9
15.3 Rectangles
Sometimes it is obvious what the attributes of an object should be, but other times you have to
make decisions.
For example, imagine you are designing a class to represent rectangles. What attributes would
you use to specify the location and size of a rectangle? You can ignore angle; to keep things
simple, assume that the rectangle is either vertical or horizontal.
There are at least two possibilities:
• You could specify one corner of the rectangle (or the center), the width, and the height.
• You could specify two opposing corners. Here is the class definition:
class Rectangle(object):
"""represent a rectangle.
attributes: width, height, corner.
"""

10
15.3 Rectangles
To represent a rectangle, you have to instantiate a Rectangle object and assign values to the
attributes:
box = Rectangle()
box.width = 100.0
box.height = 200.0
box.corner = Point()
box.corner.x = 0.0
box.corner.y = 0.0

11
15.3 Rectangles
The expression box.corner.x means, “Go to the object box refers to and select the attribute
named corner; then go to that object and select the attribute named x.”
The figure shows the state of this object:

An object that is an attribute of another object is embedded

12
15.4 Instances as return values
Functions can return instances. For example, find_center takes a Rectangle as an argument
and
returns a Point that contains the coordinates of the center of the Rectangle:
def find_center(box):
p = Point()
p.x = box.corner.x + box.width/2.0
p.y = box.corner.y + box.height/2.0
return p
Here is an example that passes box as an argument and assigns the resulting Point to center:
>>> center = find_center(box)
>>> print_point(center)
(50.0, 100.0)

13
15.4 Instances as return values
You can change the state of an object by making an assignment to one of its attributes. For
example, to change the size of a rectangle without changing its position, you can modify the
values of width and height:
box.width = box.width + 50
box.height = box.width + 100
You can also write functions that modify objects. For example, grow_rectangle takes a
Rectangle object and two numbers, dwidth and dheight, and adds the numbers to the width
and height of the rectangle:
def grow_rectangle(rect, dwidth, dheight) :
rect.width += dwidth
rect.height += dheight

14
15.4 Instances as return values
>>> print box.width
100.0
>>> print box.height
200.0
>>> grow_rectangle(box, 50, 100)
>>> print box.width
150.0
>>> print box.height
300.0
Inside the function, rect is an alias for box, so if the function modifies rect, box changes.

15
15.5 Objects are mutable
Change the state of an object by making an assignment to one of its attributes.
For example, to change the size of a rectangle without changing its position, you can modify
the values of width and height:
box.width = box.width + 50
box.height = box.width + 100
Write functions that modify objects. For example, grow_rectangle takes a Rectangle object
and two numbers, dwidth and dheight, and adds the numbers to the width and height of the
rectangle:
def grow_rectangle(rect, dwidth, dheight) :
rect.width += dwidth
rect.height += dheight

16
15.5 Objects are mutable
>>> print box.width
100.0
>>> print box.height
200.0
>>> grow_rectangle(box, 50, 100)
>>> print box.width
150.0
>>> print box.height
300.0
Inside the function, rect is an alias for box, so if the function modifies rect, box changes.

17
15.6 Copying
The copy module contains a function called copy that can duplicate any object:
>>> p1 = Point()
>>> p1.x = 3.0
>>> p1.y = 4.0
>>> import copy
>>> p2 = copy.copy(p1)
p1 and p2 contain the same data, but they are not the same Point.
>>> print_point(p1)
(3.0, 4.0)
>>> print_point(p2)
(3.0, 4.0)
>>> p1 is p2
False
>>> p1 == p2
False 18
15.6 Copying
If you use copy.copy to duplicate a Rectangle, you will find that it copies the Rectangle object
but not the embedded Point.
>>> box2 = copy.copy(box)
>>> box2 is box
False
>>> box2.corner is box.corner
True

19
Chapter 16 Classes and
Functions

20
16.1 Time
Define a class called Time that records the time of day. The class definition looks like this:
class Time(object):
"""represents the time of day.
attributes: hour, minute, second""“
Create a new Time object and assign attributes for hours, minutes, and seconds:
time = Time()
time.hour = 11
time.minute = 59
time.second = 30
The state diagram for the Time object looks like this:

21
16.1 Time
Exercise 16.1 Write a function called print_time that takes a Time object and prints it in the
form hour:minute:second. Hint: the format sequence '%.2d' prints an integer using at least two
digits, including a leading zero if necessary.

22
16.2 Pure functions
Simple prototype of add_time:
def add_time(t1, t2):
sum = Time()
sum.hour = t1.hour + t2.hour
sum.minute = t1.minute + t2.minute
sum.second = t1.second + t2.second
return sum
The function creates a new Time object, initializes its attributes, and returns a reference to the
new object.
This is called a pure function because it does not modify any of the objects passed to it as
arguments and it has no effect, like displaying a value or getting user input, other than
returning a value.

23
16.2 Pure functions
Create two Time objects: start contains the start time of a movie, like Monty Python and the
Holy Grail, and duration contains the run time of the movie, which is one hour 35 minutes.
add_time figures out when the movie will be done.
>>> start = Time()
>>> start.hour = 9
>>> start.minute = 45
>>> start.second = 0
>>> duration = Time()
>>> duration.hour = 1
>>> duration.minute = 35
>>> duration.second = 0
>>> done = add_time(start, duration)
>>> print_time(done)
10:80:00

24

You might also like