Data Science II Notes IV Units
Data Science II Notes IV Units
Algorithm A set of exact steps which when followed, solve the problem or
accomplish the required task.
Developing an Algorithm
When problems are straightforward and easy, we can easily find the
solution. But a complex problem requires a methodical approach to
find the right solution. In other words, we have to apply problem
solving techniques. Problem solving begins with the precise
identification of the problem and ends with a complete working
solution in terms of a program or software.
Analysing the problem
It is important to clearly understand a problem before we begin to
find the solution for it. If we are not clear as to what is to be
solved, we may end up developing a program which may not
solve our purpose. Thus, we need to read and analyse the
problem statement carefully in order to list the principal
components of the problem and decide the core functionalities
that our solution should have. By analysing a problem, we would be
able to figure out what are the inputs that our program should
accept and the outputs that it should produce.
Coding
After finalising the algorithm, we need to convert the
algorithm into the format which can be understood by the
computer to generate the desired solution. Different high level
programming languages can be used for writing a program.
It is equally important to record the details of the coding
procedures followed and document the solution. This is helpful
when revisiting the programs at a later stage.
Testing and Debugging
The program created should be tested on various parameters.
The program should meet the requirements of the user. It
must respond within the expected time. It should generate
correct output for all possible inputs. In the presence of
syntactical errors, no output will be obtained. In case the
output generated is incorrect, then the program should be
checked for logical errors, if any. Software industry follows
standardised testing methods like unit or component
testing, integration testing, system testing, and acceptance
testing while developing complex applications. This is to
ensure that the software meets all the business and technical
requirements and works as expected. The errors or defects
found in the testing phases are debugged or rectified and the
program is again tested. This continues
till all the errors are removed from the program.
Once the software application has been developed,
tested and delivered to the user, still problems in terms of
functioning can come up and need to be resolved from time
to time. The maintenance of the solution, thus, involves
fixing the problems faced by the user, answering the
queries of the user and even serving the request for addition
or modification of features.
ALGORITHM:
The word “algorithm” relates to the name of the mathematician Al-
khowarizmi, which means a procedure or a technique. Software Engineer
commonly uses an algorithm for planning and solving the problems. An
algorithm is a sequence of steps to solve a particular problem or algorithm is
an ordered set of unambiguous steps that produces a result and terminates in
a finite time
Advantages of algorithm
The first design of flowchart goes back to 1945 which was designed by
John Von Neumann. Unlike an algorithm, Flowchart uses different symbols
to design a solution to a problem. It is another commonly used
programming tool. By looking at a Flowchart one can understand the
operations and sequence of operations performed in a system. Flowchart
is often considered as a blueprint of a design used for solving a specific
problem.
Advantages of flowchart:
Used to represent
start and end of
Oval
flowchart
Decision making.
Used to represent
Diamond
the operation in
which there are
two/three
alternatives, true
and false etc
Pseudocode
A pseudocode (pronounced Soo-doh-kohd) is another way of representing
an algorithm. It is considered as a non-formal language that helps
programmers to write algorithm. It is a detailed description of instructions
that a computer must follow in a particular order. It is intended for human
reading and cannot be executed directly by the computer. No specific
standard for writing a pseudocode exists. The word “pseudo” means “not
real,” so “pseudocode” means “not real code”. Following are some of the
frequently used keywords while writing pseudocode:
• INPUT
• COMPUTE
• INCREMENT
• DECREMENT
• IF/ELSE
• WHILE
• TRUE/FALSE
input num1
input num2
COMPUTE Result = num1 + num2
PRINT Result
Introduction:
Python is a general-purpose interpreted, interactive, object-oriented, and
high-level programming language. It was created by Guido van Rossum
during 1985- 1990.
Python is Interpreted: Python is processed at runtime by the
interpreter. We do not need to compile our program before executing it.
Python is Interactive: We can actually sit at a Python prompt and
interact with the interpreter directly to write our programs.
Python is Object-Oriented: Python supports Object-Oriented style or
technique of programming that encapsulates code within objects.
Python is a Beginner's Language: Python is a great language for the
beginner-level programmers and supports the development of a wide
range of applications from simple text processing to WWW browsers to
games.
Python Features
Python's features include:
Easy-to-learn: Python has few keywords, simple structure, and a clearly
defined syntax. This allows the student to pick up the language quickly.
Easy-to-read: Python code is more clearly defined and visible to the
eyes.
Easy-to-maintain: Python's source code is fairly easy-to-maintain.
A broad standard library: Python's bulk of the library is very portable
and cross-platform compatible on UNIX, Windows, and Macintosh.
Interactive Mode: Python has support for an interactive mode which
allows interactive testing and debugging of snippets of code.
Portable: Python can run on a wide variety of hardware platforms and
has the same interface on all platforms.
Extendable: We can add low-level modules to the Python interpreter.
These modules enable programmers to add to or customize their tools to
be more efficient.
Databases: Python provides interfaces to all major commercial
databases.
GUI Programming: Python supports GUI applications that can be created
and ported to many system calls, libraries and windows systems, such as
Windows MFC, Macintosh, and the X Window system of Unix.
Scalable: Python provides a better structure and support for large
programs than shell scripting.
Apart from the above-mentioned features, Python has a big list of good
features, few are listed below:
It supports functional and structured programming methods as well as
OOP.
It can be used as a scripting language or can be compiled to byte-code for
building large applications.
It provides very high-level dynamic data types and supports dynamic type
checking.
IT supports automatic garbage collection.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
Python Identifiers
A Python identifier is a name used to identify a variable, function, class,
module or other object. An identifier starts with a letter A to Z or a to z or
an underscore (_) followed by zero or more letters, underscores and digits
(0 to 9). Python does not allow punctuation characters such as @, $, and
% within identifiers. Python is a case sensitive programming language.
Keywords
Keywords are the reserved words in Python. We cannot use a keyword as
variable name, function name or any other identifier.
Here's a list of all keywords in Python Programming
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else',
'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is',
'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with',
'yield']
Lines and Indentation
Python provides no braces to indicate blocks of code for class and function
definitions or flow control. Blocks of code are denoted by line indentation,
which is rigidly enforced.
The number of spaces in the indentation is variable, but all statements
within the block must be indented the same amount. For example −
if True:
print "True"
else:
print "False"
Comments in Python
A hash sign (#) that is not inside a string literal begins a comment. All
characters after the # and up to the end of the physical line are part of the
comment and the Python interpreter ignores them.
Standard Data Types
The data stored in memory can be of many types. For example, a person's
age is stored as a numeric value and his or her address is stored as
alphanumeric characters. Python has various standard data types that are
used to define the operations possible on them and the storage method
for each of them.
Python has five standard data types −
Numbers
String
List
Tuple
Dictionary
Python Numbers:
Python supports four different numerical types −
int (signed integers)
long (long integers, they can also be represented in octal and
hexadecimal)
float (floating point real values)
complex (complex numbers)
Examples
Here are some examples of numbers −
int long float complex
not Logical NOT Used to reverse the logical state of its Not(a and b) is
operand. false.
Example
var1 = 100
if var1:
print "1 - Got a true expression value"
print var1
var2 = 0
if var2:
print "2 - Got a false expression value"
print var2
print "Good bye!"
Python IF...ELIF...ELSE Statements
syntax
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
Example
var = 100
if var == 200:
print "1 - Got a true expression value"
print var
elif var == 150:
print "2 - Got a true expression value"
print var
elif var == 100:
print "3 - Got a true expression value"
print var
else:
print "4 - Got a false expression value"
print var
Python Loops
A loop statement allows us to execute a statement or group of
statements multiple times. The following diagram illustrates a loop
statement −
while loop
Syntax
while expression:
statement(s)
Flow Diagram
Example
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
print "Good bye!"
It has the ability to iterate over the items of any sequence, such as a list
or a string.
Syntax
Example
Syntax
break
Flow Diagram
Example
Syntax
continue
Flow Diagram
Example
for letter in 'Python': # First Example
if letter == 'h':
continue
print 'Current Letter :', letter
Python Functions
A function is a block of organized, reusable code that is used to
perform a single, related action.
Functions provide better modularity for our application
Functions support a high degree of code reusing.
Python gives us many built-in functions like print(), etc. but we can also
create our own functions. These functions are called user-defined
functions.
Defining a Function
Function blocks begin with the keyword def followed by the function
name and parentheses ( ( ) ).
Any input parameters or arguments should be placed within these
parentheses. we can also define parameters inside these
parentheses.
The first statement of a function can be an optional statement - the
documentation string of the function or docstring.
The code block within every function starts with a colon (:) and is
indented.
The statement return [expression] exits in a function, optionally
passing back an expression to the caller. A return statement with no
arguments is same as return None.
Syntax
Example
Defining a function only gives it a name, specifies the parameters that are
to be included in the function and structures the blocks of code.
Function Arguments
we can call a function by using the following types of formal arguments:
Required arguments
Keyword arguments
Default arguments
Variable-length arguments
Required arguments
Required arguments are the arguments passed to a function in correct
positional order. Here, the number of arguments in the function call
should match exactly with the function definition.
To call the function printme(), you definitely need to pass one argument,
otherwise it gives a syntax error as follows −
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;
# Now you can call printme function
printme()
When the above code is executed, it produces the following result:
Traceback (most recent call last):
File "test.py", line 11, in <module>
printme();
TypeError: printme() takes exactly 1 argument (0 given)
Keyword arguments
Keyword arguments are related to the function calls. When we use
keyword arguments in a function call, the caller identifies the arguments
by the parameter name.
This allows us to skip arguments or place them out of order because the
Python interpreter is able to use the keywords provided to match the
values with parameters. We can also make keyword calls to
the printme() function in the following ways −
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;
Lambda forms can take any number of arguments but return just
one value in the form of an expression. They cannot contain
commands or multiple expressions.
An anonymous function cannot be a direct call to print because
lambda requires an expression
Lambda functions have their own local namespace and cannot
access variables other than those in their parameter list and those
in the global namespace.
Although it appears that lambda's are a one-line version of a
function, they are not equivalent to inline statements in C or C++,
whose purpose is by passing function stack allocation during
invocation for performance reasons.
Syntax
The syntax of lambda functions contains only a single statement, which is
as follows −
Value of total : 30
Value of total : 40
All the above examples are not returning any value. we can return a
value from a function as follows −
Scope of Variables
All variables in a program may not be accessible at all locations in that
program. This depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you
can access a particular identifier. There are two basic scopes of variables
in Python −
Global variables
Local variables
This means that local variables can be accessed only inside the function
in which they are declared, whereas global variables can be accessed
throughout the program body by all functions. When we call a function,
the variables declared inside it are brought into scope. Following is a
simple example −
Python Modules
A module allows us to logically organize our Python code. Grouping
related code into a module makes the code easier to understand and use.
A module is a Python object with arbitrarily named attributes that we can
bind and reference.
Example
The Python code for a module named aname normally resides in a file
named aname.py. Here's an example of a simple module, support.py
Hello : Zara
For example, to import the function fibonacci from the module fib, use the
following statement −
This statement does not import the entire module fib into the current
namespace; it just introduces the item fibonacci from the module fib into
the global symbol table of the importing module.
This provides an easy way to import all the items from a module into the
current namespace;
Random numbers
To generate a whole number (integer) between one and one hundred use:
from random import *
print randint(1, 100) # Pick a random number between 1 and 100.
This will print a random integer. If you want to store it in a variable you
can use:
math.ceil(x)
Return the ceiling of x as a float, the smallest integer value greater
than or equal to x.
math.copysign(x, y)
Return x with the sign of y.
math.fabs(x)
Return the absolute value of x.
math.factorial(x)
Return x factorial.
math.trunc(x)
Return the Real value x truncated to an Integral
math.pow(x, y)
Return x raised to the power y.
math.sqrt(x)
Return the square root of x.
math.degrees(x)
Convert angle x from radians to degrees.
math.radians(x)
Convert angle x from degrees to radians.
math.pi
The mathematical constant π = 3.141592..., to available precision.
math.e
The mathematical constant e = 2.718281..., to available precision.
In Python, a function can call other functions. It is even possible for the
function to call itself. These type of construct are termed as recursive
functions.
def calc_factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * calc_factorial(x-1))
num = 4
print("The factorial of", num, "is", calc_factorial(num))
Strings
Strings are the most popular types in Python. We can create them simply
by enclosing characters in quotes. Python treats single quotes the same
as double quotes. Creating strings is as simple as assigning a value to a
variable. For example −
To access substrings, use the square brackets for slicing along with the
index or indices to obtain your substring. For example −
var1[0]: H
var2[1:5]: ytho
Updating Strings
We can "update" an existing string by (re)assigning a variable to another
string. The new value can be related to its previous value or to a
completely different string altogether. For example −
Escape Characters
Following table is a list of escape or non-printable characters that can be
represented with backslash notation.
Backslash Description
notation
\a Bell or alert
\b Backspace
\n Newline
\r Carriage return
\s Space
\t Tab
\v Vertical tab
[] Slice - Gives the character from the given index a[1] will
give e
[:] Range Slice - Gives the characters from the a[1:4] will
given range give ell
%c character
%s string conversion via str() prior to formatting
%o octal integer
Unicode String
Normal strings in Python are stored internally as 8-bit ASCII, while
Unicode strings are stored as 16-bit Unicode. This allows for a more
varied set of characters, including special characters from most
languages in the world. I'll restrict my treatment of Unicode strings to the
following −
#!/usr/bin/python
Hello, world!
capitalize()
isalnum()
Returns true if string has at least 1 character and all characters are
alphanumeric and false otherwise.
isalpha()
Returns true if string has at least 1 character and all characters are
alphabetic and false otherwise.
isdigit()
islower()
Returns true if string has at least 1 cased character and all cased
characters are in lowercase and false otherwise.
isnumeric()
isspace()
isupper()
Returns true if string has at least one cased character and all cased
characters are in uppercase and false otherwise.
len(string)
lower()
Converts all uppercase letters in string to lowercase.
lstrip()
max(str)
min(str)
upper()
Python has six built-in types of sequences, but the most common ones
are lists and tuples.
Python Lists
The list is a most flexible datatype available in Python which can be
written as a list of comma-separated values (items) between square
brackets. Important thing about a list is that items in a list need not be of
the same type.
Similar to string indices, list indices start at 0, and lists can be sliced,
concatenated and so on.
#!/usr/bin/python
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
Updating Lists
We can update single or multiple elements of lists by giving the slice on
the left-hand side of the assignment operator, and we can add to
elements in a list with the append() method. For example −
1 cmp(list1, list2)
2 len(list)
3 max(list)
4 min(list)
5 list(seq)
1 list.append(obj)
2 list.count(obj)
3 list.extend(seq)
4 list.index(obj)
5 list.insert(index, obj)
6 list.pop(obj=list[-1])
Removes and returns last object or obj from list
7 list.remove(obj)
8 list.reverse()
9 list.sort([func])
Tuples
tup1 = ();
tup1 = (50,);
Like string indices, tuple indices start at 0, and they can be sliced,
concatenated, and so on.
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]
Updating Tuples
Tuples are immutable which means you cannot update or change the
values of tuple elements. we are able to take portions of existing tuples to
create new tuples as the following example demonstrates −
To explicitly remove an entire tuple, just use the del statement. For
example:
1 cmp(tuple1, tuple2)
2 len(tuple)
3 max(tuple)
4 min(tuple)
5 tuple(seq)
Python Dictionary
Each key is separated from its value by a colon (:), the items are
separated by commas, and the whole thing is enclosed in curly braces. An
empty dictionary without any items is written with just two curly braces,
like this: {}.
Keys are unique within a dictionary while values may not be. The values
of a dictionary can be of any type, but the keys must be of an immutable
data type such as strings, numbers, or tuples.
dict['Name']: Zara
dict['Age']: 7
If we attempt to access a data item with a key, which is not part of the
dictionary, we get an error as follows −
dict['Alice']:
Traceback (most recent call last):
File "test.py", line 4, in <module>
print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'
Updating Dictionary
We can update a dictionary by adding a new entry or a key-value pair,
modifying an existing entry, or deleting an existing entry as shown below
in the simple example −
dict['Age']: 8
dict['School']: DPS School
(a) More than one entry per key not allowed. Which means no duplicate
key is allowed. When duplicate keys encountered during assignment, the
last assignment wins. For example −
dict['Name']: Manni
(b) Keys must be immutable. Which means we can use strings, numbers
or tuples as dictionary keys but something like ['key'] is not allowed.
Following is a simple example:
1 cmp(dict1, dict2)
2 len(dict)
Gives the total length of the dictionary. This would be equal to the
number of items in the dictionary.
3 str(dict)
4 type(variable)
1 dict.clear()
Removes all elements of dictionary dict
2 dict.copy()
Returns a shallow copy of dictionary dict
3 dict.fromkeys()
Create a new dictionary with keys from seq and
values set to value.
4 dict.get(key, default=None)
For key key, returns value or default if key not in dictionary
5 dict.has_key(key)
Returns true if key in dictionary dict, false otherwise
6 dict.items()
Returns a list of dict's (key, value) tuple pairs
7 dict.keys()
Returns list of dictionary dict's keys
8 dict.setdefault(key, default=None)
Similar to get(), but will set dict[key]=default if key is not already
in dict
9 dict.update(dict2)
Adds dictionary dict2's key-values pairs to dict
10 dict.values()
Returns list of dictionary dict's values
raw_input
input
This prompts you to enter any string and it would display same string on
the screen. When I typed "Hello Python!", its output is like this −
This would produce the following result against the entered input −
Syntax
file object = open(file_name [, access_mode][, buffering])
Mode Description
s
r Opens a file for reading only. The file pointer is placed at the
beginning of the file. This is the default mode.
rb Opens a file for reading only in binary format. The file pointer is
placed at the beginning of the file. This is the default mode.
r+ Opens a file for both reading and writing. The file pointer
placed at the beginning of the file.
rb+ Opens a file for both reading and writing in binary format. The
file pointer placed at the beginning of the file.
w Opens a file for writing only. Overwrites the file if the file exists.
If the file does not exist, creates a new file for writing.
wb Opens a file for writing only in binary format. Overwrites the file
if the file exists. If the file does not exist, creates a new file for
writing.
wb+ Opens a file for both writing and reading in binary format.
Overwrites the existing file if the file exists. If the file does not
exist, creates a new file for reading and writing.
a Opens a file for appending. The file pointer is at the end of the
file if the file exists. That is, the file is in the append mode. If
the file does not exist, it creates a new file for writing.
a+ Opens a file for both appending and reading. The file pointer is
at the end of the file if the file exists. The file opens in the
append mode. If the file does not exist, it creates a new file for
reading and writing.
ab+ Opens a file for both appending and reading in binary format.
The file pointer is at the end of the file if the file exists. The file
opens in the append mode. If the file does not exist, it creates a
new file for reading and writing.
Attribute Description
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
print "Closed or not : ", fo.closed
print "Opening mode : ", fo.mode
print "Softspace flag : ", fo.softspace
Syntax
fileObject.close();
Example
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
# Close opend file
fo.close()
The write() method does not add a newline character ('\n') to the end of
the string −
Syntax
fileObject.write(string);
Here, passed parameter is the content to be written into the opened file.
Example
# Open a file
fo = open("foo.txt", "wb")
fo.write( "Python is a great language.\nYeah its great!!\n");
# Close opend file
fo.close()
The above method would create foo.txt file and would write given content
in that file and finally it would close that file. If you would open this file, it
would have following content.
Syntax
fileObject.read([count]);
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Close opend file
fo.close()
File Positions
The tell() method tells us the current position within the file; in other
words, the next read or write will occur at that many bytes from the
beginning of the file.
The seek(offset[, from]) method changes the current file position.
The offset argument indicates the number of bytes to be moved.
The from argument specifies the reference position from where the bytes
are to be moved.
If from is set to 0, it means use the beginning of the file as the reference
position and 1 means use the current position as the reference position
and if it is set to 2 then the end of the file would be taken as the
reference position.
Example
Let us take a file foo.txt, which we created above.
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
The rename() method takes two arguments, the current filename and the
new filename.
Syntax
os.rename(current_file_name, new_file_name)
Example
Following is the example to rename an existing file test1.txt:
#!/usr/bin/python
import os
You can use the remove() method to delete files by supplying the name of
the file to be deleted as the argument.
Syntax
os.remove(file_name)
Example
Following is the example to delete an existing file test2.txt −
#!/usr/bin/python
import os
A file object is created using open function and here is a list of functions
which can be called on this object −
Methods with Description
file.close()
Close the file. A closed file cannot be read or written any more.
file.flush()
Flush the internal buffer, like stdio's fflush. This may be a no-op on
some file-like objects.
file.next()
Returns the next line from the file each time it is being called.
file.read([size])
Reads at most size bytes from the file (less if the read hits EOF
before obtaining size bytes).
file.readline([size])
Reads one entire line from the file. A trailing newline character is
kept in the string.
file.readlines([sizehint])
Reads until EOF using readline() and return a list containing the
lines. If the optional sizehint argument is present, instead of
reading up to EOF, whole lines totalling approximately sizehint
bytes (possibly after rounding up to an internal buffer size) are
read.
file.seek(offset[, whence])
Sets the file's current position
file.tell()
Returns the file's current position
file.write(str)
Writes a string to the file. There is no return value.
file.writelines(sequence)
Writes a sequence of strings to the file. The sequence can be any
iterable object producing strings, typically a list of strings.
Exception
An exception is an event, which occurs during the execution of a program
that disrupts the normal flow of the program's instructions. In general,
when a Python script encounters a situation that it cannot cope with, it
raises an exception. An exception is a Python object that represents an
error.
When a Python script raises an exception, it must either handle the
exception immediately otherwise it terminates and quits.
Handling an exception
If we have some suspicious code that may raise an exception, we can
defend our program by placing the suspicious code in a try: block. After
the try: block, include an except: statement, followed by a block of code
which handles the problem as elegantly as possible.
Syntax
Here is simple syntax of try....except...else blocks −
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"
fh.close()
Example
This example tries to open a file where you do not have write permission,
so it raises an exception −
#!/usr/bin/python
try:
fh = open("testfile", "r")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"
try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
......................
else:
If there is no exception then execute this block.
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
You cannot use else clause as well along with a finally clause.
Example
#!/usr/bin/python
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print "Error: can\'t find file or read data"
If you do not have permission to open the file in writing mode, then this
will produce the following result:
try:
fh = open("testfile", "w")
try:
fh.write("This is my test file for exception handling!!")
finally:
print "Going to close the file"
fh.close()
except IOError:
print "Error: can\'t find file or read data"
Creating Classes
The class statement creates a new class definition. The name of the class
immediately follows the keyword class followed by a colon as follows −
class ClassName:
'Optional class documentation string'
class_suite
Example
Following is the example of a simple Python class −
class Employee:
'Common base class for all employees'
empCount = 0
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
To create instances of a class, we call the class using class name and
pass in whatever arguments its __init__ method accepts.
Accessing Attributes
we access the object's attributes using the dot operator with object. Class
variable would be accessed using class name as follows −
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
You can add, remove, or modify attributes of classes and objects at any
time −
You normally will not notice when the garbage collector destroys an
orphaned instance and reclaims its space. But a class can implement the
special method __del__(), called a destructor, that is invoked when the
instance is about to be destroyed. This method might be used to clean up
any non memory resources used by an instance.
Example
This __del__() destructor prints the class name of an instance that is about
to be destroyed −
#!/usr/bin/python
class Point:
def __init( self, x=0, y=0):
self.x = x
self.y = y
def __del__(self):
class_name = self.__class__.__name__
print class_name, "destroyed"
pt1 = Point()
pt2 = pt1
pt3 = pt1
print id(pt1), id(pt2), id(pt3) # prints the ids of the obejcts
del pt1
del pt2
del pt3
Class Inheritance
Instead of starting from scratch, we can create a class by deriving it from
a preexisting class by listing the parent class in parentheses after the new
class name.
The child class inherits the attributes of its parent class, and we can use
those attributes as if they were defined in the child class. A child class can
also override data members and methods from the parent.
Syntax
Derived classes are declared much like their parent class; however, a list
of base classes to inherit from is given after the class name −
Example
class Parent: # define parent class
parentAttr = 100
def __init__(self):
print "Calling parent constructor"
def parentMethod(self):
print 'Calling parent method'
def setAttr(self, attr):
Parent.parentAttr = attr
def getAttr(self):
print "Parent attribute :", Parent.parentAttr
def childMethod(self):
print 'Calling child method'
Similar way, we can drive a class from multiple parent classes as follows
−
Overriding Methods
we can always override your parent class methods. One reason for
overriding parent's methods is because you may want special or different
functionality in our subclass.
Example
class Parent: # define parent class
def myMethod(self):
print 'Calling parent method'
Overloading Operators
Here we can give special meaning to operators. The below program adds
two vector objects. Here it gives special meaning to + operator. So we call
it as Operator overloading.
Example
class Vector:
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return 'Vector (%d, %d)' % (self.a, self.b)
def __add__(self,other):
return Vector(self.a + other.a, self.b + other.b)
v1 = Vector(2,10)
v2 = Vector(5,-2)
print v1 + v2
When the above code is executed, it produces the following result −
Vector(7,8)
Data Hiding
An object's attributes may or may not be visible outside the class
definition. we need to name attributes with a double underscore prefix,
and those attributes then are not be directly visible to outsiders.
Example
class JustCounter:
__secretCount = 0
def count(self):
self.__secretCount += 1
print self.__secretCount
counter = JustCounter()
counter.count()
counter.count()
print counter.__secretCount
1
2
Traceback (most recent call last):
File "test.py", line 12, in <module>
print counter.__secretCount
AttributeError: JustCounter instance has no attribute '__secretCount'
.........................
print counter._JustCounter__secretCount
1
2
2