You are on page 1of 60

Module – 5

chapter 1
Classes and Objects

1
• Python is an object oriented programming language.
• In procedure-oriented programming, where the main emphasis
is on functions, object-oriented programming stresses on
objects.
• Class: The class is a user-defined data structure that binds the
data members and methods into a single unit. Class is a blueprint
or code template for object creation. Using a class, you can create
as many objects as you want.
• Object:- An Object is an identifiable entity with some
characteristics and behavior. An Object is an instance of a
Class. When a class is defined, no memory is allocated but when
it is instantiated (i.e. an object is created) memory is allocated.
2
class

Data
members

Methods

3
Programmer-defined data type
• A class in Python can be created using a keyword class. Here, we are creating
an empty class without any members by just using the keyword pass within it.

Output

What is Module? • It indicates that the class ABC is


• module is same as a code library in the main scope of the current
module.
• To create a module just save the
• In other words, this class is at
code you want in a file with the the top level while executing the
file extension .py program. 4
• Now, a user-defined data type ABC got created, and this can be used to
create any number of objects of this class. Observe the following
statements-
p = ABC() .
• Now a reference to ABC object is created and is returned. This returned
reference is assigned to the object p.
• The process of creating a new object is called as instantiation and the object
is instance of a class.
• When we print an object, python tells which class it belongs to and where
it is stored in the memory.
print(p)
• after executing, the output displays the address of the object in the
memory. It is now clear that object occupies the physical space, where as
the class doesn't.
5
Output

6
Attributes
• An object can contain the named elements known as attributes.
• One can assign values to these attributes using dot operator.
Example:- keeping coordinate points in mind, we can assign two attributes ‘x’
and ‘y’ for the object ‘p’ of a class ABC as below:
p.x = 10.0
p.y = 20.0
• A state diagram that shows an object and its attributes is called as object
diagram.
ABC

7
• The diagram indicates that a variable ‘p’ refers to a ABC object, which
contains two attributes. Each attribute refers to a floating point number.
• One can access attributes of an object as shown –
>>> print(p.x)
10.0
>>> print(p.y)
20.0
Here, p.x -> “got to the object p refers to and get the value of x”.
• Attributes of an object can be assigned to other variables –
>>>x = p.x
>>>print(x)
10.0
8
9
• '''This is a class Point representing a coordinate point’‘’ represents the
docstring. It is an important part of documentation and is to help someone
to understand the purpose of the said class/module/function.
• The docstring becomes a value for the special attribute viz. __doc__
available for any class ( and objects of that class).
• To get the value of docstring associated with a class, one can use the
statements like –
>>>print(Point.__doc__)
This is a class Point representing a coordinate point
>>> print(p1.__doc__)
This is a object representing a coordinate point

10
11
• Euclidean distance between two points (x1,y1) and (x2,y2) is
(x1,y1) = (10,20)
(x2,y2) = (3,5)

In this program, we have Point objects as (p1.x, p1.y) and (p2.x, p2.y). Apply
the formula on these points by passing objects p1 and p2 as parameters to the
function distance(). And then return the result.

12
Types of Attributes
• User-defined classes in python have two types of attributes
viz. class attributes and instance attributes
• Class attributes :- are defined inside the class(usually
immediately after class header). They are common to all
objects of that class. They are shared by all the objects
created from that class.
• Instance attributes :- they are defined for individual
objects. They are available only for that object. Attributes
of one object are not available for another object of the same
class.
13
• This clearly indicates that the attributes ‘x’ and ‘y’ created are available only for the object
p1 but not for p2. Thus, x and y are instance attributes but not class attributes.
14
• An example of class attributes is illustrated below with the help of
program:

The attributes x and y are defined inside


the definition of the class Point itself.
Hence they are available to all the
objects of that class

Output
15
Copying
• An object will be aliased whenever an object is assigned to another object
of same class.
• Let us understand the concept of aliasing more in detail using the following
program.
• Observe that both p1 and p2 objects have same physical
memory. It is clear now that the object p2 is an alias for p1.
so, we can draw the object diagram as below -

16
• But the aliasing is not good always. For example we may need to create a
new object using an existing object such that – the new object should have
a different physical memory, but it must have same attribute (and their
values) as that of existing object.

• We “need a copy of an object, but not an alias”. To do this, Python provides


a module called copy and a method called copy(). Concept has been
illustrated below with the help of program.

17
18
Shallow copying:- it copies the object and any references it contains, but
not the embedded objects.
• The attributes width and height for two objects box1 and box2 are
independent. Whereas the attribute corner is shared by both the objects.
Thus any modification done to box1.corner will reflect box2.corner as well.

19
20
Deep copy():-
• Whenever we create a duplicate objects, we want two independent
physical objects. Python provides a method deepcopy( ) for doing
this task. This method copies not only the object but also the
objects it refers to, and the objects they refer to, and so on.
• In the program, the objects box1 and box2 are now completely
independent.

21
22
Rectangle Program Output

23
Chapter – 2
Classes and Functions
24
Pure Functions
• To understand the concept of pure functions, lets us consider an
example of creating a class called as “Time”.
• An object of class time contains hour, minutes, and seconds as
attributes.
• Write a function to print time in HH:MM:SS format and another
function to add two time objects.
• The function add_time() takes two arguments of type Time, and
returns a Time object, whereas it is not modifying contents of its
arguments t1 and t2. such functions are called as pure
functions.
• %.2d -> prints an integer using atleast two digits, including a
leading zero if necessary. 25
Output1

26
Output 2

27
Output 3

28
Modifiers
• Sometimes, it is necessary to modify the underlying argument so as
to reflect the caller. That is, arguments have to be modified inside a
function and these modifications should be available to the caller.
The functions that perform such modifications are known as modifier
function.

Output
29
30
Output

31
32

CHAPTER – 3
CLASSES AND METHODS
Object Oriented features
• Python is an object oriented programming language, which means that it provides
features that support object-oriented programming, which has these defining
characteristics:
1. Programs include class and method definitions.
2. Most of the computation is expressed in terms of operations on objects.
3. Objects often represent things in the real world, and methods often correspond to
the ways things in the real world interact.
• A method is a function that is associated with a particular class. We have seen
methods for strings, lists, dictionaries and tuples.
• Methods are semantically the same as functions, but there are two syntactic
differences:
1. Methods are defined inside a class definition in order to make the relationship
between the class and the method explicit.
33
2. The syntax for invoking a method is different from the syntax for calling a
Printing Objects
• Below is the program which shows a class named Time and a function named
print_time.

Output

34
• To make a print_time as a method, move the function definition inside the
class definition. Notice the change in the indentation.

35
• There are two ways to call print_time:-
1. The first way is to use function syntax:
>>>Time.print_time(start)
09:45:00
Here, Time is the name of class, and print_time is the name of the method.
start is passed as a parameter.
2. The second way is to use method syntax:
>>>start.print_time()
09:45:00
Here, print_time is the name of the method, and start is the object, the
method is invoked on, which is called as subject. start is assigned to the time.

36
Output

37
38
First parameter of method is called “self”
• Self is a default variable that contains the memory address of the instance
of the current class. So we can use ‘self’ to refer to all the instance
variables and instance methods.
• When an instance to the class is created, the instance name contains the
memory location of the instance. This memory location is internally passed
to “self”. For example, we create an instance to the Student class as:
S1 = Student()
Here, S1 contains the memory address of the instance. This memory address
is internally and by default passed to “Self” variable. Since “Self” knows the
memory address of the instance, it can refer to all the members of the
instance.
• We use “self” in two ways:

39
1. “self” variable is used as a first parameter in the constructor as:
def __init__(self):
in this case, “self” can be used to refer to the instance variables inside the
constructor.
2. “self” can be used as a first parameter in the instance methods as:
def talk(self):
here, talk() is the instance method as it acts on the instance variables. If this
method wants to act on the instance variables, it should know the memory
location of the instance variables. That memory location is by default available
to the talk() method through “self”.
what is constructor?
Constructor is a special method that is used to initialize the instance variables
of a class.
40
The init method
• The init method is automatically executed when an object of a class is
created.
• This method is useful to initialize the variables of the class object.

Output

41
Output

42
43
44
The _ _ str_ _ method
• This is a special method, that is supposed to return a string representation of
an object.

45
• When I create any object, constructor will be executed.
• Constructor will be executed as many times as number of objects are
created.
• The main purpose of constructor is to declare and initialize the instance
variables.
• Self is used to point to the current object.

46
Example program to compare constructor and
method 47
48
Operator Overloading

• Changing the behaviour of an


operator, so that it works on
user defined types(classes) is
called operator overloading.
• Basic Operators like +, -, *,
etc can be overloaded. To
overload an operator, one
needs to write a
method(special method)
within user-defined class.

49
p3=

50
51
Program to overload the + operator
on a complex object

52
Program to compare two objects of
user defined type

53
Polymorphism
• The word polymorphism means having many forms.
• In programming, polymorphism means the same function name (but
different signatures) being used for different types. The key difference is
the data types and number of arguments used in function.

54
55
Example Programs

56
A python program using a student class with instance methods to process the data of
several students.

57
58
59
Count the total number of digits in a
number

60

You might also like