0% found this document useful (0 votes)
7 views9 pages

Python Programming: Classes and Objects

This document introduces Python programming concepts related to classes and objects, specifically focusing on defining programmer-defined types. It explains how to represent points and rectangles using classes, the importance of attributes, and the differences between shallow and deep copying of objects. Additionally, it covers object-oriented features such as the init method, operator overloading, and type-based dispatch in the context of a Time class.

Uploaded by

sanjanabr0707
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)
7 views9 pages

Python Programming: Classes and Objects

This document introduces Python programming concepts related to classes and objects, specifically focusing on defining programmer-defined types. It explains how to represent points and rectangles using classes, the importance of attributes, and the differences between shallow and deep copying of objects. Additionally, it covers object-oriented features such as the init method, operator overloading, and type-based dispatch in the context of a Time class.

Uploaded by

sanjanabr0707
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

INTRODUCTION TO PYTHON PROGRAMMING (B25PLC15B)

MODULE 5
Prepared By:
Prof. Senthil kumar
Dept. of ISE
DBIT Bengaluru

Classes and objects


Programmer-defined types

In mathematical notation, points are often written in parentheses with a comma


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.

Creating a new type is more complicated than the other options, but it has advantages that
will be apparent soon.
A programmer-defined type is also called a class. A class definition looks like this:

class Point:
"""Represents a point in 2-D space."""

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 [Link] or [Link]. In this case, though, we are assigning
values to named elements of an object. These elements are called attributes.

DBIT 1|Page
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 ig-
nore 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.

height
corner

class Rectangle:
"""Represents a rectangle.

attributes: width, height,


corner. """
The docstring lists the attributes: width and height are numbers; corner is a
Point object that specifies the lower-left corner.

To represent a rectangle, you have to instantiate a Rectangle object and assign


values to the attributes:
box = Rectangle()
[Link] = 100.0
[Link] = 200.0
[Link] = Point()
[Link].x = 0.0
[Link].y = 0.0
The expression [Link].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.”

Above Figure shows the state of this object. An object that is an attribute of another
object is
embedded.
DBIT 2|Page
Objects are mutable

Copying
Aliasing can make a program difficult to read because changes in one place might have
unexpected effects in another place. It is hard to keep track of all the variables that might
refer to a given object.
Copying an object is often an alternative to aliasing. The copy module contains a function
called copy that can duplicate any object:
>>> p1 = Point()
>>> p1.x = 3.0
>>> p1.y = 4.0

DBIT 3|Page
>>> import copy
>>> p2 = [Link](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
The is operator indicates that p1 and p2 are not the same object, which is
what we expected.
But you might have expected == to yield True because these points contain
the same data.
In that case, you will be disappointed to learn that for instances, the default
behavior of the
== operator is the same as the is operator; it checks object identity, not
object equivalence.
Another Example :-

If you use [Link] to duplicate a Rectangle, you will find that it copies
the Rectangle
object but not the embedded Point.
>>> box2 = [Link](box)
>>> box2 is box
False
>>> [Link] is [Link]
True
Above figure shows what the object diagram looks like. This operation is
called a shallow
copy because it copies the object and any references it contains, but not the
embedded
objects.
DBIT 4|Page
Fortunately, the copy module contains a method named deepcopy that
copies not only the
object but also the objects it refers to, and the objects they refer to, and so
on. You will not
be surprised to learn that this operation is called a deep copy.
>>> box3 = [Link](box)
>>> box3 is box
False
>>> [Link] is [Link]
False
box3 and box are completely separate objects.

Time
As another example of a programmer-defined type, we’ll define a class called Time that
records the time of day. The class definition looks like this:
class Time:
"""Represents the time of day.

attributes: hour, minute,


second """
We can create a new Time object and assign attributes for hours, minutes, and seconds:
time = Time()
[Link] = 11
[Link] = 59
[Link] = 30

Pure functions
In the next few sections, we’ll write two functions that add time values. They
demonstrate two kinds of functions: pure functions and modifiers. They also
demonstrate a develop- ment plan I’ll call prototype and patch, which is a way
of tackling a complex problem by starting with a simple prototype and
incrementally dealing with the complications.
Here is a simple prototype of add_time:
def add_time(t1, t2):
sum = Time()
[Link] = [Link] + [Link]
[Link] = [Link] + [Link]
[Link] = [Link] + [Link]
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.
DBIT 5|Page
Classes and methods

Object-oriented features
Python is an object-oriented programming language, which means that it provides fea-
tures that support object-oriented programming, which has these defining characteristics:

• Programs include class and method definitions.


• Most of the computation is expressed in terms of operations on objects.
• Objects often represent things in the real world, and methods often
correspond to the ways things in the real world interact.

The init method

The init method (short for “initialization”) is a special method that gets invoked
when an object is instantiated. Its full name is init (two underscore
characters, followed by init, and then two more underscores). An init method
for the Time class might look like this:
# inside class Time:

def init (self, hour=0, minute=0, second=0):


[Link] = hour
[Link] = minute
[Link] = second

The __str__method
Str__is a special method, like init , that is supposed to return a string representa-
tion of an object.
For example, here is a str method for Time objects:
# inside class Time:

def str (self):


return '%.2d:%.2d:%.2d' % ([Link], [Link],
[Link])
When you print an object, Python invokes the str method:
>>> time = Time(9, 45)
>>> print(time)
09:45:00

Operator overloading
DBIT 6|Page
By defining other special methods, you can specify the behavior of operators on
programmer-defined types. For example, if you define a method named add for the
Time class, you can use the + operator on Time objects.

def add (self, other):


seconds = self.time_to_int()
other.time_to_int()
return int_to_time(seconds)

Changing the behavior of an operator so that it works with user-defined types is called
operator overloading.

Type-based dispatch
In the previous section we added two Time objects, but you also might want to
add an integer to a Time object. The following is a version of add that checks
the type of other and invokes either add_time or increment:
# inside class Time:

def add (self, other):


if isinstance(other,
Time): return
self.add_time(other)
else:
return [Link](other)

def add_time(self, other):


seconds = self.time_to_int() +
other.time_to_int() return
int_to_time(seconds)

def increment(self, seconds):


DBIT 7|Page
seconds += self.time_to_int()
return int_to_time(seconds)
The built-in function isinstance takes a value and a class object, and returns True if the
value is an instance of the class.
If other is a Time object, __add__ invokes add_time. Otherwise it assumes that the parameter
is a number and invokes increment. This operation is called a type-based dispatch
because it dispatches the computation to different methods based on the type of the
arguments.
Here are examples that use the + operator with different types:
>>> start = Time(9, 45)
>>> duration = Time(1, 35)
>>> print start + duration
11:20:00
>>> print start + 1337
10:07:17
Unfortunately, this implementation of addition is not commutative. If the integer is the
first operand, you get
>>> print 1337 + start
TypeError: unsupported operand type(s) for +: 'int' and 'instance'

Polymorphism
Type-based dispatch is useful when it is necessary, but (fortunately) it is not always neces-
sary. Often you can avoid it by writing functions that work correctly for arguments with
different types.
Many of the functions we wrote for strings also work for other sequence types. For exam-
ple, in Section 11.2 we used histogram to count the number of times each letter appears
in a word.

DBIT 8|Page
DBIT 9|Page

You might also like