[go: up one dir, main page]

0% found this document useful (0 votes)
6 views39 pages

Oops 1 Notes

introduction to python with oops
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)
6 views39 pages

Oops 1 Notes

introduction to python with oops
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
You are on page 1/ 39

Module-I

Introduction to Python and Object Oriented Concepts

Introduction to Python

Programming languages like C, Pascal or FORTRAN concentrate more on the functional aspects of
programming. In these languages, there will be more focus on writing the code using functions. For
example, we can imagine a C program as a combination of several functions. Computer scientists
thought that programming will become easy for human beings to understand if it is based on real life
examples.

Hence, they developed Object Oriented Programming languages like Java and .NET where
programming is done through classes and objects. Programmers started migrating from C to Java and
Java soon became the most popular language in the software community. In Java, a programmer
should express his logic through classes and objects only. It is not possible to write a program without
writing at least one class! This makes programming lengthy.

For example, a simple program to add two numbers in Java looks like this:

//Java program to add two numbers

class Add //create a class

public static void main(String args[]) //start execution

int a, b; //take two variables

a = b = 10; //store 10 in to a, b

System.out.println("Sum= "+ (a+b)); //display their sum

Python

Python is a programming language that combines the features of C and Java. It offers elegant style of
developing programs like C. When the programmers want to go for object orientation, Python offers
classes and objects like Java. In Python, the program to add two numbers will be as follows:

#Python program to add two numbers

a = b = 10 #take two variables and store 10 in to them

print("Sum=", (a+b)) #display their sum

2
Van Rossum picked the name Python for the new language from the TV show, Monty Python‘s
Flying Circus. Python‘s first working version was ready by early 1990 and Van Rossum released it for
the public on February 20, 1991. The logo of Python shows two intertwined snakes as shown in
Figure 1.1.

Python is open source software, which means anybody can freely download it from www.python.org
and use it to develop programs. Its source code can be accessed and modified as required in the
projects.

Features of Python

There are various reasons why Python is gaining good popularity in the programming community.
The following are some of the important features of Python:

1. Simple: Python is a simple programming language. When we read a Python program, we feel
like reading English sentences. It means more clarity and less stress on understanding the
syntax of the language. Hence, developing and understanding programs will become easy.

2. Easy to learn: Python uses very few keywords. Its programs use very simple structure. So,
developing programs in Python become easy. Also, Python resembles C language. Most of
the language constructs in C are also available in Python. Hence, migrating from C to Python
is easy for programmers.

3. Open source: There is no need to pay for Python software. Python can be freely downloaded
from www.python.org website. Its source code can be read, modified and can be used in
programs as desired by the programmers.

4. High level language: Programming languages are of two types: low level and high level. A
low level language uses machine code instructions to develop programs. These instructions
directly interact with the CPU. Machine language and assembly language are called low level
languages. High level languages use English words to develop programs. These are easy to
learn and use. Like COBOL, PHP or Java, Python also uses English words in its programs
and hence it is called high level programming language.

5. Dynamically typed: In Python, we need not declare anything. An assignment statement


binds a name to an object, and the object can be of any type. If a name is assigned to an
object of one type, it may later be assigned to an object of a different type. This is the
meaning of the saying that Python is a dynamically typed language. Languages like C and
Java are statically typed. In these languages, the variable names and data types should be
mentioned properly. Attempting to assign an object of the wrong type to a variable name
triggers error or exception.

3
6. Platform independent: When a Python program is compiled using a Python compiler, it
generates byte code. Python‘s byte code represents a fixed set of instructions that run on all
operating systems and hardware. Using a Python Virtual Machine (PVM), anybody can run
these byte code instructions on any computer system. Hence, Python programs are not
dependent on any specific operating system. We can use Python on almost all operating
systems like UNIX, Linux, Windows,Macintosh, Solaris, OS/2, Amiga, AROS, AS/400, etc.
This makes Python an ideal programming language for any network or Internet.

7. Portable: When a program yields the same result on any computer in the world, then it is
called a portable program. Python programs will give the same result since they are platform
independent. Once a Python program is written, it can run on any computer system using
PVM. However, Python also contains some system dependent modules (or code), which are
specific to operating system. Programmers should be careful about such code while
developing the software if they want it to be completely portable.

8. Procedure and object oriented: Python is a procedure oriented as well as an object oriented
programming language. In procedure oriented programming languages (e.g. C and Pascal),
the programs are built using functions and procedures. But in object oriented languages (e.g.
C++ and Java), the programs use classes and objects.

Let‘s get some idea on objects and classes. An object is anything that exists physically in the real
world. Almost everything comes in this definition. Let‘s take a dog with the name Snoopy. We can
say Snoopy is an object since it physically exists in our house. Objects will have behavior represented
by their attributes (or properties) and actions. For example, Snoopy has attributes like height, weight,
age and color. These attributes are represented by variables in programming. Similarly, Snoopy can
perform actions like barking, biting, eating, running, etc. These actions are represented by methods
(functions) in programming. Hence, an object contains variables and methods.

A class, on the other hand, does not exist physically. A class is only an abstract idea which represents
common behavior of several objects. For example, dog is a class. When we talk about dog, we will
have a picture in our mind where we imagine a head, body, legs, tail, etc. This imaginary picture is
called a class. When we take Snoopy, she has all the features that we have in our mind but she exists
physically and hence she becomes the object of dog class. Similarly all the other dogs like Tommy,
Charlie, Sophie, etc. exhibit same behavior like Snoopy. Hence, they are all objects of the same class,
i.e. dog class. We should understand the point that the object Snoopy exists physically but the class
dog does not exist physically. It is only a picture in our mind with some attributes and actions at
abstract level. When we take Snoopy, Tommy, Charlie and Sophie, they have these attributes and
actions and hence they are all objects of the dog class.

A class indicates common behavior of objects. This common behavior is represented by attributes and
actions. Attributes are represented by variables and actions are performed by methods (functions). So,
a class also contains variables and methods just like an object does. Figure 1.2 shows relationship
between a class and its object:

4
Fig: A Class and its object

Similarly, parrot, sparrow, pigeon and crow are objects of the bird class. We should understand that
bird (class) is only an idea that defines some attributes and actions. A parrot and sparrow have the
same attributes and actions but they exist physically. Hence, they are objects of the bird class.

Object oriented languages like Python, Java and .NET use the concepts of classes and objects in their
programs. Since class does not exist physically, there will not be any memory allocated when the
class is created. But, object exists physically and hence, a separate block of memory is allocated when
an object is created. In Python language, everything like variables, lists, functions, arrays etc. are
treated as objects.

a. Interpreted: A program code is called source code. After writing a Python program, we should
compile the source code using Python compiler. Python compiler translates the Python
program into an intermediate code called byte code. This byte code is then executed by PVM.
Inside the PVM, an interpreter converts the byte code instructions into machine code so that
the processor will understand and run that machine code to produce results.

b. Extensible: The programs or pieces of code written in C or C++ can be integrated into Python
and executed using PVM. This is what we see in standard Python that is downloaded from
www.python.org. There are other flavors of Python where programs from other languages can
be integrated into Python. For example, Jython is useful to integrate Java code into Python
programs and run on JVM (Java Virtual Machine). Similarly, Iron Python is useful to
integrate .NET programs and libraries into Python programs and run on CLR (Common
Language Runtime).

c. Embeddable: We can insert Python programs into a C or C++ program. Several applications
are already developed in Python which can be integrated into other programming languages
like C, C++, Delphi, PHP, Java and .NET. It means programmers can use these applications
for their advantage in various software projects.

5
d. Huge library: Python has a big library which can be used on any operating system like UNIX,
Windows or Macintosh. Programmers can develop programs very easily using the modules
available in the Python library.

e. Scripting language: A scripting language is a programming language that does not use a
compiler for executing the source code. Rather, it uses an interpreter to translate the source
code into machine code on the fly (while running). Generally, scripting languages perform
supporting tasks for a bigger application or software. For example, PHP is a scripting
language that performs supporting task of taking input from an HTML page and send it to
Web server software. Python is considered as a scripting language as it is interpreted and it is
used on the Internet to support other software.

f. Database connectivity: A database represents software that stores and manipulates data. For
example, Oracle is a popular database using which we can store data in the form of tables and
manipulate the data. Python provides interfaces to connect its programs to all major databases
like Oracle, Sybase or MySql.

g. Scalable: A program would be scalable if it could be moved to another operating system or


hardware and take full advantage of the new environment in terms of performance. Python
programs are scalable since they can run on any platform and use the features of the new
platform effectively.

h. Batteries included: The huge library of Python contains several small applications (or small
packages) which are already developed and immediately available to programmers. These
small packages can be used and maintained easily. Thus the programmers need not download
separate packages or applications in many cases. This will give them a head start in many
projects. These libraries are called ‗batteries included‘.

Some interesting batteries or packages are given here:

1. botois Amazon web services library

2. cryptography offers cryptographic techniques for the programmers

3. Fiona reads and writes big data files

4. jellyfish is a library for doing approximate and phonetic matching of strings

5. mysql-connector-pythonis a driver written in Python to connect to MySQL database

6. numpy is a package for processing arrays of single or multidimensional type

7. pandas is a package for powerful data structures for data analysis, time series and statistics

8. matplotlib is a package for drawing electronic circuits and 2D graphs.

9. pyquery represents jquery-like library for Python

10. w3lib is a library of web related functions

6
Data types in Python

We have already written a Python program to add two numbers and executed it. Let‘s now view the
program once again here:

#First Python program to add two numbers

a = 10

b = 15

c=a+b

print("Sum=", c)

When we compile this program using Python compiler, it converts the program source code into byte
code instructions. This byte code is then converted into machine code by the interpreter inside the
Python Virtual Machine (PVM). Finally, the machine code is executed by the processor in our
computer and the result is produced as:

F:\PY>python first.py

Sum= 25

Observe the first line in the program. It starts with the #symbol. This is called the comment line. A
comment is used to describe the features of a program. When we write a program, we may write some
statements or create functions or classes, etc. in our program. All these things should be described
using comments. When comments are written, not only our selves but also any programmer can easily
understand our program. It means comments increase readability (understandability) of our programs.

Comments in Python

There are two types of comments in Python: single line comments and multi line comments. Single
line comments .These comments start with a hash symbol (#) and are useful to mention that the entire
line till the end should be treated as comment. For example,

#To find sum of two numbers

a = 10 #store 10 into variable a

Here, the first line is starting with a #and hence the entire line is treated as a comment. In the second
line, a = 10 is a statement. After this statement, #symbol starts the comment describing that the value
10 is stored into variable ‗a‘. The part of this line starting from #symbol to the end is treated as a
comment. Comments are non-executable statements. It means neither the Python compiler nor the
PVM will execute them.

Multi line comments

When we want to mark several lines as comment, then writing #symbol in the beginning of every line
will be a tedious job. For example,

#This is a program to find net salary of an employee

#based on the basic salary, provident fund, house rent allowance,

7
#dearness allowance and income tax.

Instead of starting every line with #symbol, we can write the previous block of code inside """ (triple
double quotes) or ''' (triple single quotes) in the beginning and ending of the block as:

""" This is a program to find net salary of an employee based on the basic salary, provident fund,
house rent allowance, dearness allowance and income tax. """

The triple double quotes (""") or triple single quotes (''') are called ‗multi line comments‘ or ‗block
comments‘. They are used to enclose a block of lines as comments.

Data types in Python

A data type represents the type of data stored into a variable or memory. The data types which are
already available in Python language are called Built-in data types. The data types which can be
created by the programmers are called User-defined data types. The built-in data types are of five
types:

1. None Type

2. Numeric types

3. Sequences

4. Sets

5. Mappings

None Type

In Python, the ‗None‘ data type represents an object that does not contain any value. In languages like
Java, it is called ‗null‘ object. But in Python, it is called ‗None‘ object. In a Python program,
maximum of only one ‗None‘ object is provided. One of the uses of ‗None‘ is that it is used inside a
function as a default value of the arguments. When calling the function, if no value is passed, then the
default value will be taken as ‗None‘. If some value is passed to the function, then that value is used
by the function. In Boolean expressions, ‗None‘ data type represents ‗False‘.

Numeric Types

The numeric types represent numbers. There are three sub types:

 int

 float

 complex

Int Data type

The int data type represents an integer number. An integer number is a number without any decimal
point or fraction part. For example, 200, -50, 0, 9888998700, etc. are treated as integer numbers. Now,
let‘s store an integer number -57 into a variable ‗a‘.

a = -57

8
Here, ‗a‘ is called int type variable since it is storing -57 which is an integer value. In Python, there is
no limit for the size of an int data type. It can store very large integer numbers conveniently.

Float Data type

The float data type represents floating point numbers. A floating point number is a number that
contains a decimal point. For example, 0.5, -3.4567, 290.08, 0.001 etc. are called floating point
numbers. Let‘s store a float number into a variable ‗num‘ as:

num = 55.67998

Here num is called float type variable since it is storing floating point value. Floating point numbers
can also be written in scientific notation where we use ‗e‘ or ‗E‘ to represent the power of 10. Here ‗e‘
or ‗E‘ represents ‗exponentiation‘. For example, the number 2.5 × 104 is written as 2.5E4. Such
numbers are also treated as floating point numbers. For example,

x = 22.55e3

Here, the float value 22.55 × 103 is stored into the variable ‗x‘. The type of the variable ‗x‘ will be
internally taken as float type. The convenience in scientific notation is that it is possible to represent
very big numbers using less memory.

Complex Data type

A complex number is a number that is written in the form of a + bj or a + bJ. Here, ‗a‘ represents the
real part of the number and ‗b‘ represents the imaginary part of the number. The suffix ‗j‘ or ‗J‘ after
‗b‘ indicates the square root value of -1. The parts ‗a‘ and ‗b‘ may contain integers or floats. For
example, 3+5j, -1-5.5J, 0.2+10.5J are all complex numbers. See the following statement:

c1 = -1-5.5J

Representing Binary, Octal and Hexadecimal Numbers

A binary number should be written by prefixing 0b (zero and b) or 0B (zero and B) before the value.
For example, 0b110110, 0B101010011 are treated as binary numbers. Hexadecimal numbers are
written by prefixing 0x (zero and x) or 0X (zero and big X) before the value, as 0xA180 or 0X11fb91
etc. Similarly, octal numbers are indicated by prefixing 0o (zero and small o) or 0O (zero and then O)
before the actual value. For example, 0O145 or 0o773 are octal values. Converting the Data types
Explicitly Depending on the type of data, Python internally assumes the data type for the variable. But
sometimes, the programmer wants to convert one data type into another type on his own. This is
called type conversion or coercion. This is possible by mentioning the data type with parentheses. For
example, to convert a number into integer type, we can write int(num).

int(x) is used to convert the number x into int type. See the example:

x = 15.56

int(x) #will display 15

float(x) is used to convert x into float type.

9
For example,

num = 15 float(num) #will display 15.0

Bool Data type

The bool data type in Python represents boolean values. There are only two boolean values True or
False that can be represented by this data type. Python internally represents True as 1 and False as 0.
A blank string like "" is also represented as False. Conditions will be evaluated internally to either
True or False. For example,

a = 10

b = 20

if(a<b):

print("Hello") #displays Hello.

In the previous code, the condition a<b which is written after if - is evaluated to True and hence it will
execute print("Hello").

a = 10>5 #here ‗a‘ is treated as bool type variable

print(a) #displays True

a = 5>10

print(a) #displays False

True+True will display 2 #True is 1 and false is 0

True-False will display 1

Sequences in Python

Generally, a sequence represents a group of elements or items. For example, a group of integer
numbers will form a sequence. There are six types of sequences in Python:

1. str

2. bytes

3. bytearray

4. list

5. tuple

6. range

Str Data type

In Python, str represents string data type. A string is represented by a group of characters. Strings are
enclosed in single quotes or double quotes. Both are valid.

10
str = ―Welcome‖ #here str is name of string type variable

We can also write strings inside """ (triple double quotes) or ''' (triple single quotes) to span a group of
lines including spaces.

Bytes Data type

The bytes data type represents a group of byte numbers just like an array does. A byte number is any
positive integer from 0 to 255 (inclusive). bytes array can store numbers in the range from 0 to 255
and it cannot even store negative numbers. For example,

elements = [10, 20, 0, 40, 15] #this is a list of byte numbers

x = bytes(elements) #convert the list into bytes array

print(x[0]) #display 0th element, i.e 10

We cannot modify or edit any element in the bytes type array. For example, x[0] = 55 gives an error.
Here we are trying to replace 0th element (i.e. 10) by 55 which is not allowed.

Bytearray Data type

The bytearray data type is similar to bytes data type. The difference is that the bytes type array cannot
be modified but the bytearray type array can be modified. It means any element or all the elements of
the bytearray type can be modified. To create a bytearray type array, we can use the function
bytearray as:

elements = [10, 20, 0, 40, 15] #this is a list of byte numbers

x = bytearray(elements) #convert the list into bytearray type array

print(x[0]) #display 0th element, i.e 10

We can modify or edit the elements of the bytearray. For example, we can write: x[0] = 88 #replace
0th element by 88 x[1] = 99 #replace 1st element by 99.

List Data type

Lists in Python are similar to arrays in C or Java. A list represents a group of elements. The main
difference between a list and an array is that a list can store different types of elements but an array
can store only one type of elements. Also, lists can grow dynamically in memory. But the size of
arrays is fixed and they cannot grow at runtime. Lists are represented using square brackets [] and the
elements are written in [], separated by commas. For example,

list = [10, -20, 15.5, 'Vijay', "Mary"]

will create a list with different types of elements. The slicing operation like [0: 3] represents elements
from 0th to 2nd positions, i.e. 10, 20, 15.5.

Tuple Data type

A tuple is similar to a list. A tuple contains a group of elements which can be of different types. The
elements in the tuple are separated by commas and enclosed in parentheses (). Whereas the list

11
elements can be modified, it is not possible to modify the tuple elements. That means a tuple can be
treated as a read-only list. Let‘s create a tuple as:

tpl = (10, -20, 15.5, 'Vijay', "Mary")

The individual elements of the tuple can be referenced using square braces as tpl[0], tpl[1], tpl[2], …
Now, if we try to modify the 0th element as:

tpl[0] = 99

This will result in error. The slicing operations which can be done on lists are also valid in tuples.

Range Data type

The range data type represents a sequence of numbers. The numbers in the range are not modifiable.
Generally, range is used for repeating a for loop for a specific number of times. To create a range of
numbers, we can simply write:

r = range(10)

Here, the range object is created with the numbers starting from 0 to 9.

Sets

A set is an unordered collection of elements much like a set in Mathematics. The order of elements is
not maintained in the sets. It means the elements may not appear in the same order as they are entered
into the set. Moreover, a set does not accept duplicate elements. There are two sub types in sets:

 set data type

 frozenset data type

Set Data type

To create a set, we should enter the elements separated by commas inside curly braces {}.

s = {10, 20, 30, 20, 50}

print(s) #may display {50, 10, 20, 30}

Please observe that the set ‗s‘ is not maintaining the order of the elements. We entered the elements in
the order 10, 20, 30, 20 and 50. But it is showing another order. Also, we repeated the element 20 in
the set, but it has stored only one 20. We can use the set() function to create a set as:

ch = set("Hello")

print(ch) #may display {'H', 'e', 'l', 'o'}

Here, a set ‗ch‘ is created with the characters H,e,l,o. Since a set does not store duplicate elements, it
will not store the second ‗l‘.

12
frozenset Data type

The frozenset data type is same as the set data type. The main difference is that the elements in the set
data type can be modified; whereas, the elements of frozenset cannot be modified. We can create a
frozenset by passing a set to frozenset() function as:

s = {50,60,70,80,90}

print(s) #may display {80, 90, 50, 60, 70}

fs = frozenset(s) #create frozenset fs

print(fs) #may display frozenset({80, 90, 50, 60, 70})

Mapping Types

A map represents a group of elements in the form of key value pairs so that when the key is given, we
can retrieve the value associated with it. The dict datatype is an example for a map. The ‗dict‘
represents a ‗dictionary‘ that contains pairs of elements such that the first element represents the key
and the next one becomes its value. The key and its value should be separated by a colon (:) and every
pair should be separated by a comma. All the elements should be enclosed inside curly brackets {}.
We can create a dictionary by typing the roll numbers and names of students. Here, roll numbers are
keys and names will become values. We write these key value pairs inside curly braces as:

d = {10: 'Kamal', 11: 'Pranav', 12: 'Hasini', 13: 'Anup', 14: 'Reethu'}

Here, d is the name of the dictionary. 10 is the key and its associated value is ‗Kamal‘.

The next key is 11 and its value is ‗Pranav‘. Similarly 12 is the key and ‗Hasini‘ is it value. 13 is the
key and ‗Anup‘ is the value and 14 is the key and ‗Reethu‘ is the value. We can create an empty
dictionary without any elements as:

d = {}

Literals in Python

A literal is a constant value that is stored into a variable in a program. Observe the following
statement:

a = 15

Here, ‗a‘ is the variable into which the constant value ‗15‘ is stored. Hence, the value 15 is called
‗literal‘. Since 15 indicates integer value, it is called ‗integer literal‘. The following are different types
of literals in Python.

1. Numeric literals

2. Boolean literals

3. String literals

13
Numeric Literals

Examples Literal name

450, -15 Integer literal

3.14286, -10.6, 1.25E4 Float literal

These literals represent numbers. Please observe the different types of numeric literals available in
Python.

Boolean Literals

Boolean literals are the True or False values stored into a bool type variable.

String Literals

A group of characters is called a string literal. These string literals are enclosed in single quotes (') or
double quotes (") or triple quotes ('''or"""). In Python, there is no difference between single quoted
strings and double quoted strings. Single or double quoted strings should end in the same line as:

s1 = 'This is first Indian book'

s2 = "Core Python"

User-defined Data types

The data types which are created by the programmers are called ‗user-defined‘ data types. For
example, an array, a class, or a module is user-defined data types.

Constants in Python

A constant is similar to a variable but its value cannot be modified or changed in the course of the
program execution. We know that the variable value can be changed whenever required. But that is
not possible for a constant. Once defined, a constant cannot allow changing its value. For example, in
Mathematics, ‗pi‘ value is 22/7 which never changes and hence it is a constant. In languages like C
and Java, defining constants is possible. But in Python, that is not possible. A programmer can
indicate a variable as constant by writing its name in all capital letters. For example, MAX_VALUE
is a constant. But its value can be changed.

Identifiers and Reserved words

An identifier is a name that is given to a variable or function or class etc. Identifiers can include
letters, numbers, and the underscore character (_). They should always start with a nonnumeric
character. Special symbols such as?, #, $,%, and @ are not allowed in identifiers. Some examples for
identifiers are salary, name11, gross_income, etc. We should also remember that Python is a case
sensitive programming language. It means capital letters and small letters are identified separately by
Python. For example, the names ‗num‘ and ‗Num‘ are treated as different names and hence represent
different variables. Figure 3.12 shows examples of a variable, an operator and a literal:

14
Reserved words are the words that are already reserved for some particular purpose in the Python
language. The names of these reserved words should not be used as identifiers. The following are the
reserved words available in Python:

Naming Conventions in Python

Python developers made some suggestions to the programmers regarding how to write names in the
programs. The rules related to writing names of packages, modules, classes, variables, etc. are called
naming conventions. The following naming conventions should be followed:

1. Packages: Package names should be written in all lower case letters. When multiple words are
used for a name, we should separate them using an underscore (_).

2. Modules: Modules names should be written in all lower case letters. When multiple words are
used for a name, we should separate them using an underscore (_).

3. Classes: Each word of a class name should start with a capital letter. This rule is applicable for
the classes created by us. Python‘s built-in class names use all lowercase words. When a class
represents exception, then its name should end with a word ‗Error‘.

15
4. Global variables or Module-level variables: Global variables names should be all lower case
letters. When multiple words are used for a name, we should separate them using an
underscore (_).

5. Instance variables: Instance variables names should be all lower case letters. When multiple
words are used for a name, we should separate them using an underscore (_). Non-public
instance variable name should begin with an underscore.

6. Functions: Function names should be all lower case letters. When multiple words are used for a
name, we should separate them using an underscore (_).

Operators in python

Operator An operator is a symbol that performs an operation. An operator acts on some variables
called operands. For example, if we write a + b, the operator ‗ + ‗ is acting on two operands ‗a‘ and
‗b‘. If an operator acts on a single variable, it is called unary operator. If an operator acts on two
variables, it is called binary operator. If an operator acts on three variables, then it is called ternary
operator. This is one type of classification. We can classify the operators depending upon their nature,
as shown below:

1. Arithmetic operators

2. Assignment operators

3. Unary minus operator

4. Relational operators

5. Logical operators

6. Boolean operators

7. Bitwise operators

Input and output

The purpose of a computer is to process data and return results. It means that first of all, we should
provide data to the computer. The data given to the computer is called input. The results returned by
the computer are called output. So, we can say that a computer takes input, processes that input and
produces the output.

16
To provide input to a computer, Python provides some statements which are called Input statements.
Similarly, to display the output, there are Output statements available in Python. We should use some
logic to convert the input into output. This logic is implemented in the form of several topics in
subsequent chapters. We will discuss the input and output statements in this chapter, but in the
following order:

 Output statements

 Input statements

Output statements

To display output or results, Python provides the print() function. This function can be used in
different formats.

The print() Statement

When the print() function is called simply, it will throw the cursor to the next line. It means that a
blank line will be displayed.

The print(formatted string)

Statement The output displayed by the print() function can be formatted as we like. The special
operator ‗%‘ (percent) can be used for this purpose. It joins a string with a variable or value in the
following format:

print(―formatted string‖% (variables list))

In the ―formatted string‖, we can use %i or %d to represent decimal integer numbers. We can use %f
to represent float values. Similarly, we can use %s to represent strings. See the example below:

x=10

print('value= %i'% x)

value= 10

As seen above, to display a single variable (i.e. ‗x‘), we need not wrap it inside parentheses.

Input Statements

To accept input from keyboard, Python provides the input () function. This function takes a value
from the keyboard and returns it as a string. For example,

str = input('Enter your name:')

Enter your name: Raj kumar

print(str)

Raj kumar

17
Control Statements

Control statements are statements which control or change the flow of execution. The following are
the control statements available in Python:

1. if statement

2. if … else statement

3. if … elif … else statement

4. while loop

5. for loop

6. else suite

7. break statement

8. continue statement

9. pass statement

10. assert statement

11. return statement

The if Statement

This statement is used to execute one or more statement depending on whether a condition is True or
not. The syntax or correct format of if statement is given below:

if condition:

statements

First, the condition is tested. If the condition is True, then the statements given after colon (:) are
executed. We can write one or more statements after colon (:). If the condition is False, then the
statements mentioned after colon are not executed.

The if … else Statement

The if … else statement executes a group of statements when a condition is True; otherwise, it will
execute another group of statements. The syntax of if … else statement is given below:

if condition:

statements1

else:

statements2

If the condition is True, then it will execute statements1 and if the condition is False, then it will
execute statements2. It is advised to use 4 spaces as indentation before statements1 and statements2.

18
The if … elif … else Statement

Sometimes, the programmer has to test multiple conditions and execute statements depending on
those conditions. if … elif … else statement is useful in such situations. Consider the following syntax
of if … elif … else statement:

if condition1:

statements1

elif condition2:

statements2

else:

statements3

When condition1 is True, the statements1 will be executed. If condition1 is False, then condition2 is
evaluated. When condition2 is True, the statements2 will be executed. When condition 2 is False, the
statements3 will be executed. It means statements3 will be executed only if none of the conditions are
True.

The while Loop

A statement is executed only once from top to bottom. For example, ‗if‘ is a statement that is executed
by Python interpreter only once. But a loop is useful to execute repeatedly. For example, while and
for are loops in Python. They are useful to execute a group of statements repeatedly several times.

The while loop is useful to execute a group of statements several times repeatedly depending on
whether a condition is True or False. The syntax or format of while loop is:

while condition:

statements

The for Loop

The for loop is useful to iterate over the elements of a sequence. It means, the for loop can be used to
execute a group of statements repeatedly depending upon the number of elements in the sequence.
The for loop can work with sequence like string, list, tuple, range etc. The syntax of the for loop is
given below:

for var in sequence:

statements

The else Suite

In Python, it is possible to use ‗else‘ statement along with for loop or while loop. The statements
written after ‗else‘ are called suite. The else suite will be always executed irrespective of the
statements in the loop are executed or not. For example,

19
for i in range(5):

print("Yes")

else:

print("No")

The break Statement

The break statement can be used inside a for loop or while loop to come out of the loop. When ‗break‘
is executed, the Python interpreter jumps out of the loop to process the next statement in the program.
Now, suppose we want to display x values up to 6 and if it is 5 then we want to come out of the loop,
we can introduce a statement like this:

if x==5: #if x is 5 then come out from while loop

break

The continue Statement

The continue statement is used in a loop to go back to the beginning of the loop. It means, when
continue is executed, the next repetition will start. When continue is executed, the subsequent
statements in the loop are not executed.

The pass Statement

The pass statement does not do anything. It is used with ‗if‘ statement or inside a loop to represent no
operation. We use pass statement when we need a statement syntactically but we do not want to do
any operation.

The assert Statement

The assert statement is useful to check if a particular condition is fulfilled or not.

assert expression, message

In the above syntax, the ‗message‘ is not compulsory. Let‘s take an example. If we want to assure that
the user should enter only a number greater than 0, we can use assert statement as:

assert x>0, "Wrong input entered"

In this case, the Python interpreter checks if x>0 is True or not. If it is True, then the next statements
will execute, else it will display AssertionError along with the message ―Wrong input entered‖.

The return Statement

A function represents a group of statements to perform a task. The purpose of a function is to perform
some task and in many cases a function returns the result. A function starts with the keyword defthat
represents the definition of the function. After ‗def‘, the function should be written. Then we should
write variables in the parentheses. For example,

def sum(a, b):

20
function body

After the function name, we should use a colon (:) to separate the name with the body. The body of
the statements contains logic to perform the task. For example, to find sum of two numbers, we can
write: def

sum(a, b):

print(a+b)

A function is executed only when it is called. At the time of calling the sum() function, we should
pass values to variables a and b. So, we can call this function as:

sum(5, 10)

Now, the values 5 and 10 are passed to a and b respectively and the sum() function displays their
sum. In Program 30, we will now write a simple function to perform sum of two numbers.

Introduction to Object Oriented Concepts

Languages like C++, Java and Python use classes and objects in their programs and are called Object
Oriented Programming languages. A class is a module which itself contains data and methods
(functions) to achieve the task. The main task is divided into several sub tasks, and these are
represented as classes. Each class can perform several inter-related tasks for which several methods
are written in a class. This approach is called Object Oriented approach.

Features of Object Oriented Programming System (OOPS)

There are five important features related to Object Oriented Programming System. They are:

21
1. Classes and objects

2. Encapsulation

3. Abstraction

4. Inheritance

5. Polymorphism

Classes and Objects

An object is anything that really exists in the world and can be distinguished from others. This
definition specifies that everything in this world is an object. For example, a table, a ball, a car, a dog,
a person, etc. will come under objects. Then what is not an object? If something does not really exist,
then it is not an object. For example, our thoughts, imagination, plans, ideas etc. are not objects,
because they do not physically exist.

Encapsulation

Encapsulation is a mechanism where the data (variables) and the code (methods) that act on the data
will bind together. For example, if we take a class, we write the variables and methods inside the
class. Thus, class is binding them together. So class is an example for encapsulation.

The variables and methods of a class are called ‗members‘ of the class. All the members of a class are
by default available outside the class. That means they are public by default. Public means available
to other programs and classes.

Encapsulation in Python

Encapsulation is nothing but writing attributes (variables) and methods inside a class. The methods
process the data available in the variables. Hence data and code are bundled up together in the class.

22
For example, we can write a Student class with ‗id‘ and ‗name as attributes along with the display()
method that displays this data. This Student class becomes an example for encapsulation.

Abstraction

There may be a lot of data, a class contains and the user does not need the entire data. The user
requires only some part of the available data. In this case, we can hide the unnecessary data from the
user and expose only that data that is of interest to the user. This is called abstraction.

A good example for abstraction is a car. Any car will have some parts like engine, radiator, battery,
mechanical and electrical equipment etc. The user of the car (driver) should know how to drive the car
and does not require any knowledge of these parts. For example driver is never bothered about how
the engine is designed and the internal parts of the engine. This is why the car manufacturers hide
these parts from the driver in a separate panel, generally at the front of the car.

Inheritance

Creating new classes from existing classes, so that the new classes will acquire all the features of the
existing classes is called Inheritance. A good example for Inheritance in nature is parents producing
the children and children inheriting the qualities of the parents.

Let‘s take a class A with some members i.e., variables and methods. If we feel another class B wants
almost same members, then we can derive or create class B from A as:

class B(A):

Now, all the features of A are available to B. If an object to B is created, it contains all the members
of class A and also its own members. Thus, the programmer can access and use all the members of
both the classes A and B. Thus, class B becomes more useful. This is called inheritance. The original
class (A) is called the base class or super class and the derived class (B) is called the sub class or
derived class.

Polymorphism

The word ‗Polymorphism‘ came from two Greek words ‗poly‘ meaning ‗many‘ and ‗morphos‘
meaning ‗forms‘. Thus, polymorphism represents the ability to assume several different forms. In
programming, if an object or method is exhibiting different behavior in different contexts, it is called
polymorphic nature.

Polymorphism provides flexibility in writing programs in such a way that the programmer uses same
method call to perform different operations depending on the requirement.

23
Module – II

Python Classes and Objects


We know that a class is a model or plan to create objects. This means, we write a class with the
attributes and actions of objects. Attributes are represented by variables and actions are performed by
methods. So, a class contains variable and methods. The same variables and methods are also
available in the objects because they are created from the class. These variables are also called
‗instance variables‘ because they are created inside the instance (i.e. object). Please remember the
difference between a function and a method. A function written inside a class is called a method.
Generally, a method is called using one of the following two ways:

 class name.methodname()

 instancename.methodname()

The general format of a class is given as follows:

Class Classname(object):

""" docstring describing the class """

attributes def __init__(self):

def method1():

def method2():

Creating a Class

A class is created with the keyword class and then writing the Classname. After the Classname,
‗object‘ is written inside the Classname. This ‗object‘ represents the base class name from where all
classes in Python are derived. Even our own classes are also derived from ‗object‘ class. Hence, we
should mention ‗object‘ in the parentheses. Please note that writing ‗object‘ is not compulsory since it
is implied.

For example, a student has attributes like name, age, marks, etc. These attributes should be written
inside the Student class as variables. Similarly, a student can perform actions like talking, writing,
reading, etc. These actions should be represented by methods in the Student class. So, the class
Student contains these attributes and actions, as shown here:

class Student:

#another way is:

class Student(object):

#the below block defines attributes

def __init__(self):

self.name = ‗Vishnu‘

24
self.age = 20

self.marks = 900

#the below block defines a method

def talk(self):

print(‗Hi, I am ‗, self.name)

print(‗My age is‘, self.age)

print(‗My marks are‘, self.marks)

See the method talk(). This method also takes the ‗self‘ variable as parameter. This method displays
the values of the variables by referring them using ‗self‘.

The methods that act on instances (or objects) of a class are called instance methods. Instance
methods use ‗self‘ as the first parameter that refers to the location of the instance in the memory.
Since instance methods know the location of instance, they can act on the instance variables. In the
previous code, the two methods __init__(self) and talk(self) are called instance methods. In the
Student class, a student is talking to us through talk() method. He is introducing himself to us, as
shown here: Hi, I am Vishnu My age is 20 My marks are 900 This is what the talk() method
displays. Writing a class like this is not sufficient. It should be used. To use a class, we should create
an instance (or object) to the class. Instance creation represents allotting memory necessary to store
the actual data of the variables, i.e., Vishnu, 20 and 900. To create an instance, the following syntax is
used:

instancename = Classname()

So, to create an instance (or object) to the Student class, we can write as:

s1 = Student()

Here, ‗s1‘ is nothing but the instance name. When we create an instance like this, the following steps
will take place internally:

1. First of all, a block of memory is allocated on heap. How much memory is to be allocated is
decided from the attributes and methods available in the Student class.

2. After allocating the memory block, the special method by the name ‗__init__(self)‘ is called
internally. This method stores the initial data into the variables. Since this method is useful to
construct the instance, it is called ‗constructor‘.

3. Finally, the allocated memory location address of the instance is returned into ‗s1‘ variable. To see
this memory location in decimal number format, we can use id() function as id(s1).

Now, ‗s1‘ refers to the instance of the Student class. Hence any variables or methods in the instance
can be referenced by ‗s1‘ using dot operator as:

s1.name #this refers to data in name variable, i.e. Vishnu

s1.age #this refers to data in age variable, i.e. 20

25
s1.marks #this refers to data in marks variable, i.e. 900

s1.talk() #this calls the talk() method.

The dot operator takes the instance name at its left and the member of the instance at the right hand
side. Figure 2.1 shows how ‗s1‘ instance of Student class is created in memory:

Figure 2.1: Student class instance in memory

Program

Program 1: A Python program to define Student class and create an object to it. Also, we will call the
method and display the student‘s details.

#instance variables and instance method

class Student:

#this is a special method called constructor.

def __init__(self):

self.name = 'Vishnu'

self.age = 20

self.marks = 900

#this is an instance method.

def talk(self):

print('Hi, I am', self.name)

print('My age is', self.age)

print('My marks are', self.marks)

#create an instance to Student class.

s1 = Student()

#call the method using the instance.

26
s1.talk()

Output:

C:\>python cl.py

Hi, I am Vishnu

My age is 20

My marks are 900

In Program 1, we used the ‗self‘ variable to refer to the instance of the same class. Also, we used a
special method ‗__init__(self)‘ that initializes the variables of the instance. Let‘s have more clarity on
these two concepts.

The Self Variable

‗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 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:

 The ‗self‘ variable is used as 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.

 ‗self‘ can be used as first parameter in the instance methods as:

def talk(self):

Here, talk() is 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‘.

Constructor

A constructor is a special method that is used to initialize the instance variables of a class. In the
constructor, we create the instance variables and initialize them with some starting values. The first
parameter of the constructor will be ‗self‘ variable that contains the memory address of the instance.
For example,

def __init__(self):

self.name = ‗Vishnu‘

27
self.marks = 900

Here, the constructor has only one parameter, i.e. ‗self‘. Using ‗self.name‘ and ‗self.marks‘, we can
access the instance variables of the class. A constructor is called at the time of creating an instance.
So, the above constructor will be called when we create an instance as:
s1 = Student()

Here, ‗s1‘ is the name of the instance. Observe the empty parentheses after the class name ‗Student‘.
These empty parentheses represent that we are not passing any values to the constructor. Suppose, we
want to pass some values to the constructor, then we have to pass them in the parentheses after the
class name. Let‘s take another example. We can write a constructor with some parameters in addition
to ‗self‘ as:

def __init__(self, n = ‗‘, m=0):

self.name = n

self.marks = m

Here, the formal arguments are ‗n‘ and ‗m‘ whose default values are given as ‗‘ (None) and 0 (zero).
Hence, if we do not pass any values to constructor at the time of creating an instance, the default
values of these formal arguments are stored into name and marks variables. For example,

s1 = Student()

Since we are not passing any values to the instance, None and zero are stored into name and marks.
Suppose, we create an instance as:

s1 = Student(‗Lakshmi Roy‘, 880)

In this case, we are passing two actual arguments: ‗Lakshmi Roy‘ and 880 to the Student instance.
Hence these values are sent to the arguments ‗n‘ and ‗m‘ and from there stored into name and marks
variables. We can understand this concept from Program.

Program

Program 2: A Python program to create Student class with a constructor having more than one
parameter.

#instance vars and instance method - v.20

class Student:

#this is constructor.

def __init__(self, n ='', m=0):

self.name = n

self.marks = m

#this is an instance method.

def display(self):

28
print('Hi', self.name)

print('Your marks', self.marks)

#constructor is called without any arguments

s = Student()

s.display()

print('------------------')

#constructor is called with 2 arguments

s1 = Student('Lakshmi Roy', 880)

s1.display()

print('------------------')

Output:

C:\>python cl.py

Hi

Your marks 0

------------------

Hi Lakshmi Roy

Your marks 880

------------------

We should understand that a constructor does not create an instance. The duty of the constructor is to
initialize or store the beginning values into the instance variables. A constructor is called only once at
the time of creating an instance. Thus, if 3 instances are created for a class, the constructor will be
called once per each instance, thus it is called 3 times.

Types of Variables

The variables which are written inside a class are of 2 types:

 Instance variables

 Class variables or Static variables

Instance variables are the variables whose separate copy is created in every instance (or object). For
example, if ‗x‘ is an instance variable and if we create 3 instances, there will be 3 copies of ‗x‘ in
these 3 instances. When we modify the copy of ‗x‘ in any instance, it will not modify the other two
copies. Consider Program.

29
Program

Program 3: A Python program to understand instance variables.

#instance vars example

class Sample:

#this is a constructor.

def __init__(self):

self.x = 10

#this is an instance method.

def modify(self):

self.x+=1

#create 2 instances

s1 = Sample()

s2 = Sample()

print(‗x in s1= ‗, s1.x)

print(‗x in s2= ‗, s2.x)

#modify x in s1

s1.modify()

print(‗x in s1= ‗, s1.x)

print(‗x in s2= ‗, s2.x)

Output: C:\>python cl.py

x in s1= 10

x in s2= 10

x in s1= 11

x in s2= 10

Instance variables are defined and initialized using a constructor with ‗self‘ parameter. Also, to
access instance variables, we need instance methods with ‗self‘ as first parameter. It is possible that
the instance methods may have other parameters in addition to the ‗self‘ parameter. To access the
instance variables, we can use self.variable as shown in Program. It is also possible to access the
instance variables from outside the class, as: instancename.variable, e.g. s1.x.

30
Unlike instance variables, class variables are the variables whose single copy is available to all the
instances of the class. If we modify the copy of class variable in an instance, it will modify all the
copies in the other instances. For example, if ‗x‘ is a class variable and if we create 3 instances, the
same copy of ‗x‘ is passed to these 3 instances. When we modify the copy of ‗x‘ in any instance using
a class method, the modified copy is sent to the other two instances. This can be easily grasped from
Program. Class variables are also called static variables.

Program

Program 4: A Python program to understand class variables or static variables.

#class vars or static vars example

class Sample:

#this is a class var

x = 10

#this is a class method.

@classmethod

def modify(cls):

cls.x+=1

#create 2 instances

s1 = Sample()

s2 = Sample()

print(‗x in s1= ‗, s1.x)

print(‗x in s2= ‗, s2.x)

#modify x in s1

s1.modify()

print(‗x in s1= ‗, s1.x)

print(‗x in s2= ‗, s2.x)

Output: C:\>python cl.py

x in s1= 10

x in s2= 10

x in s1= 11

x in s2= 11

31
Observe Program. The class variable ‗x‘ is defined in the class and initialized with value 10. A
method by the name ‗modify‘ is used to modify the value of ‗x‘. This method is called ‗class method‘
since it is acting on the class variable. To mark this method as class method, we should use built-in
decorator statement @classmethod. For example,

@classmethod #this is a decorator

def modify(cls): #cls must be the first parameter

cls.x+=1 #cls.x refers to class variable x

Namespaces

A namespace represents a memory block where names are mapped (or linked) to objects. Suppose we
write:

n = 10

Here, ‗n‘ is the name given to the integer object 10. Please recollect that numbers, strings, lists etc. are
all considered as objects in Python. The name ‗n‘ is linked to 10 in the namespace. A class maintains
its own namespace, called ‗class namespace‘. In the class namespace, the names are mapped to class
variables. Similarly, every instance will have its own name space, called ‗instance namespace‘. In the
instance namespace, the names are mapped to instance variables. In the following code, ‗n‘ is a class
variable in the Student class. So, in the class namespace, the name ‗n‘ is mapped or linked to 10 as
shown Figure 2. Since it is a class variable, we can access it in the class namespace, using
classname.variable, as: Student.n which gives 10.

Figure 2: Modifying the class variable in the class namespace

#understanding class namespace

class Student:

#this is a class var

n=10

#access class var in the class namespace

print(Student.n)

#displays 10

Student.n+=1

32
#modify it in class namespace

print(Student.n)

#displays 11

We know that a single copy of class variable is shared by all the instances. So, if the class variable is
modified in the class namespace, since same copy of the variable is modified, the modified copy is
available to all the instances. This is shown in Figure 2.

#modified class var is seen in all instances

s1 = Student() #create s1 instance

print(s1.n) #displays 11

s2 = Student() #create s2 instance

print(s2.n) #displays 11

If the class variable is modified in one instance namespace, it will not affect the variables in the other
instance namespaces. This is shown in Figure 3. To access the class variable at the instance level, we
have to create instance first and then refer to the variable as instancename.variable.

Figure 3: Modifying the class variable in the instance namespace

#understanding instance namespace

class Student:

#this is a class var

n=10

#access class var in the s1 instance namespace

s1 = Student() print(s1.n)

#displays 10

s1.n+=1

#modify it in s1 instance namespace

print(s1.n) #displays 11

33
As per the above code, we created an instance ‗s1‘ and modified the class variable ‗n‘ in that instance.
So, the modified value of ‗n‘ can be seen only in that instance. When we create other instances like
‗s2‘, there will be still the original value of ‗n‘ available. See the code below:

#modified class var is not seen in other instances

s2 = Student()

#this is another instance

print(s2.n) #displays 10, not 11

Types of Methods

The purpose of a method is to process the variables provided in the class or in the method. We already
know that the variables declared in the class are called class variables (or static variables) and the
variables declared in the constructor are called instance variables. We can classify the methods in the
following 3 types:

 Instance methods (a) Accessor methods (b) Mutator methods

 Class methods

 Static methods

Instance Methods

Instance methods are the methods which act upon the instance variables of the class. Instance
methods are bound to instances (or objects) and hence called as: instancename.method(). Since
instance variables are available in the instance, instance methods need to know the memory address of
the instance. This is provided through ‗self‘ variable by default as first parameter for the instance
method. While calling the instance methods, we need not pass any value to the ‗self‘ variable.

In this program, we are creating a Student class with a constructor that defines ‗name‘ and ‗marks‘ as
instance variables. An instance method display() will display the values of these variables. We added
another instance methods by the name calculate() that calculates the grades of the student depending
on the ‗marks‘.

Program

Program 5: A Python program using a student class with instance methods to process the data of
several students.

#instance methods to process data of the objects

class Student:

#this is a constructor.

def __init__(self, n = ‗‘, m=0):

self.name = n

self.marks = m

34
#this is an instance method.

def display(self):

print(‗Hi‘, self.name)

print(‗Your marks‘, self.marks)

#to calculate grades based on marks.

def calculate(self):

if(self.marks>=600):

print(‗You got first grade‘)

elif(self.marks>=500):

print(‗You got second grade‘)

elif(self.marks>=350):

print(‗You got third grade‘)

else:

print(‗You are failed‘)

#create instances with some data from keyboard

n = int(input(‗How many students? ‗))

i=0

while(i<n):

name = input(‗Enter name: ‗)

marks = int(input(‗Enter marks: ‗))

#create Student class instance and store data

s = Student(name, marks)

s.display()

s.calculate()

i+=1

print(‗---------------------‗)

Output:

C:\>python cl.py

35
How many students? 3

Enter name: Vishnu Vardhan

Enter marks: 800

Hi Vishnu Vardhan

Your marks 800

You got first grade ---------------------

Enter name: Tilak Prabhu

Enter marks: 360

Hi Tilak Prabhu

Your marks 360

You got third grade ---------------------

Enter name: Gunasheela

Enter marks: 550

Hi Gunasheela

Your marks 550

You got second grade ---------------------

Instance methods are of two types: accessor methods and mutator methods. Accessor methods simply
access or read data of the variables. They do not modify the data in the variables. Accessor methods
are generally written in the form of getXXX() and hence they are also called getter methods. For
example,

def getName(self):

return self.name

Here, getName() is an accessor method since it is reading and returning the value of ‗name‘ instance
variable. It is not modifying the value of the name variable. On the other hand, mutator methods are
the methods which not only read the data but also modify them. They are written in the form of
setXXX() and hence they are also called setter methods. For example,

def setName(self, name):

self.name = name

Here, setName() is a mutator method since it is modifying the value of ‗name‘ variable by storing
new name. In the method body, ‗self.name‘ represents the instance variable ‗name‘ and the right hand
side ‗name‘ indicates the parameter that receives the new value from outside. In Program, we are
redeveloping the Student class using accessor and mutator methods.

36
Program

Program 6: A Python program to store data into instances using mutator methods and to retrieve data
from the instances using accessor methods.

#accessor and mutator methods class

Student:

#mutator method

def setName(self, name):

self.name = name

#accessor method

def getName(self):

return self.name

#mutator method

def setMarks(self, marks):

self.marks = marks

#accessor method

def getMarks(self):

return self.marks

#create instances with some data from keyboard

n = int(input(‗How many students? ‗))

i=0

while(i<n):

#create Student class instance

s = Student()

name = input(‗Enter name: ‗)

s.setName(name)

marks = int(input(‗Enter marks: ‗))

s.setMarks(marks)

#retrieve data from Student class instance

print(‗Hi‘, s.getName())

37
print(‗Your marks‘, s.getMarks())

i+=1 print(‗-------------------‗)

Output:

C:\>python cl.py

How many students? 2

Enter name: Vinay Krishna

Enter marks: 890

Hi Vinay Krishna

Your marks 890

------------------

Enter name: Vimala Rao

Enter marks: 750

Hi Vimala Rao

Your marks 750

------------------

Since mutator methods define the instance variables and store data, we need not write the constructor
in the class to initialize the instance variables. This is the reason we did not use constructor in Student
class in the above Program.

Class Methods

These methods act on class level. Class methods are the methods which act on the class variables or
static variables. These methods are written using @classmethod decorator above them. By default, the
first parameter for class methods is ‗cls‘ which refers to the class itself. For example, ‗cls.var‘ is the
format to refer to the class variable. These methods are generally called using the classname.method().
The processing which is commonly needed by all the instances of the class is handled by the class
methods. In Program 7, we are going to develop Bird class. All birds in the Nature have only 2 wings.
So, we take ‗wings‘ as a class variable. Now a copy of this class variable is available to all the
instances of Bird class. The class method fly() can be called as Bird.fly().

Program

Program 7: A Python program to use class method to handle the common feature of all the instances
of Bird class.

#understanding class methods class Bird:

#this is a class var wings = 2

38
#this is a class method

@classmethod

def fly(cls, name):

print(‗{} flies with {} wings‘.format(name, cls.wings))

#display information for 2 birds

Bird.fly(‗Sparrow‘)

Bird.fly(‗Pigeon‘)

Output:

C:\>python cl.py

Sparrow flies with 2 wings

Pigeon flies with 2 wings

Static Methods

We need static methods when the processing is at the class level but we need not involve the class or
instances. Static methods are used when some processing is related to the class but does not need the
class or its instances to perform any work. For example, setting environmental variables, counting the
number of instances of the class or changing an attribute in another class, etc. are the tasks related to
a class. Such tasks are handled by static methods. Also, static methods can be used to accept some
values, process them and return the result. In this case the involvement of neither the class nor the
objects is needed. Static methods are written with a decorator @staticmethod above them. Static
methods are called in the form of classname.method(). In Program 8, we are creating a static method
noObjects() that counts the number of objects or instances created to Myclass. In Myclass, we have
written a constructor that increments the class variable ‗n‘ every time an instance is created. This
incremented value of ‗n‘ is displayed by the noObjects() method.

Program

Program 8: A Python program to create a static method that counts the number of instances created
for a class.

#understanding static methods class Myclass:

#this is class var or static var

n=0

#constructor that increments n when an instance is created

def __init__(self):

Myclass.n = Myclass.n+1

#this is a static method to display the no. of instances

39
@staticmethod def noObjects():

print(‗No. of instances created: ‗, Myclass.n)

#create 3 instances

obj1 = Myclass()

obj2 = Myclass()

obj3 = Myclass()

Myclass.noObjects()

Output:

C:\>python cl.py

No. of instances created: 3

In the next program, we accept a number from the keyboard and return the result of its square root
value. Here, there is no need of class or object and hence we can write a static method to perform this
task.

40

You might also like