0% found this document useful (0 votes)
15 views33 pages

Unit 4

Uploaded by

Md Jafar Sadiqe
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)
15 views33 pages

Unit 4

Uploaded by

Md Jafar Sadiqe
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/ 33

Functions- Introduction, Function Definition, the return statement, Required Arguments, Keyword

Arguments, Default Arguments, Variable length Arguments.


Object Oriented Programming: Features of OOP, Merits and Demerits of OOP, Defining
Classes, Creating Objects, Data Abstraction, and Hiding through classes, Class Method and Self
Argument, The init () method, Public and Private data members, Private Methods.

Functions
In Python, a function is a group of related statements that performs a specific task.
Functions help break our program into smaller and modular chunks. As our program grows larger and
larger, functions make it more organized and manageable.
Furthermore, it avoids repetition and makes the code reusable.

A function is a block of code which only runs when it is called.


You can pass data, known as parameters, into a function.
A function can return data as a result.

A function is a block of organized, reusable code that is used to perform a single, related action.
Functions provide better modularity for your application and a high degree of code reusing.

Syntax of Function

def function_name(parameters):
"""docstring"""
statement(s)

Above shown is a function definition that consists of the following components.

1. Keyword def that marks the start of the function header.


2. A function name to uniquely identify the function. Function naming follows the same rules of writing
identifiers in Python.
3. Parameters (arguments) through which we pass values to a function. They are optional.
4. A colon (:) to mark the end of the function header.
5. Optional documentation string (docstring) to describe what the function does.
6. One or more valid python statements that make up the function body. Statements must have the same
indentation level (usually 4 spaces).
7. An optional return statement to return a value from the function.

Example of a function

def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")

How to call a function in python?


Once we have defined a function, we can call it from another function, program or even the Python
prompt. To call a function we simply type the function name with appropriate parameters.

>>> greet('Students')
Hello, Students. Good morning!

Note: Try running the above code in the Python program with the function definition to see the output.

def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")

greet('Students')

Calling a Function
To call a function, use the function name followed by parenthesis:
Example
def my_function():
print("Pragati Engineering College")

my_function()

How Function works in Python?

Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When the function is called,
we pass along a first name, which is used inside the function to print the full name:

def my_function(fname):
print(fname+ "Students")

my_function("Pragati")
my_function("CSE")
my_function("Section B")

Output:
Pragati Students
CSE Students
Section B Students

Function Arguments
You 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
# 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()

Keyword arguments
Keyword arguments are related to the function calls. When you use keyword arguments in a function
call, the caller identifies the arguments by the parameter name.
This allows you 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. You can also make keyword calls to
the printme() function in the following ways −
#!/usr/bin/python

# 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( str = "My string")

When the above code is executed, it produces the following result − My string
The following example gives more clear picture. Note that the order of parameters does not matter.
#!/usr/bin/python

# Function definition is here


def printinfo( name, age ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;

# Now you can call printinfo function


printinfo( age=50, name="miki" )
When the above code is executed, it produces the following result −
Name: miki
Age 50

Default arguments
A default argument is an argument that assumes a default value if a value is not provided in the function
call for that argument. The following example gives an idea on default arguments, it prints default age if
it is not passed −
#!/usr/bin/python

# Function definition is here


def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;

# Now you can call printinfo function


printinfo( age=50, name="miki" )
printinfo( name="miki" )
When the above code is executed, it produces the following result −
Name: miki
Age 50
Name: miki
Age 35

Variable-length arguments
You may need to process a function for more arguments than you specified while defining the function.
These arguments are called variable-length arguments and are not named in the function definition,
unlike required and default arguments.
Syntax for a function with non-keyword variable arguments is this −
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
An asterisk (*) is placed before the variable name that holds the values of all nonkeyword variable
arguments. This tuple remains empty if no additional arguments are specified during the function call.
Following is a simple example −
#!/usr/bin/python

# Function definition is here


def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print "Output is: "
print arg1
for var in vartuple:
print var
return;

# Now you can call printinfo function


printinfo( 10 )
printinfo( 70, 60, 50 )
When the above code is executed, it produces the following result −
Output is:
10
Output is:
70
60
50

The Anonymous Functions


These functions are called anonymous because they are not declared in the standard manner by using
the def keyword. You can use the lambda keyword to create small anonymous functions.
 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 −
lambda [arg1 [,arg2,.....argn]]:expression
Following is the example to show how lambda form of function works −
#!/usr/bin/python

# Function definition is here


sum = lambda arg1, arg2: arg1 + arg2;

# Now you can call sum as a function


print "Value of total : ", sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )
When the above code is executed, it produces the following result −
Value of total : 30
Value of total : 40
The return Statement
The statement return [expression] exits a function, optionally passing back an expression to the caller. A
return statement with no arguments is the same as return None.
The return statement is used to exit a function and go back to the place from where it was called.

Syntax of return

return [expression_list]

This statement can contain an expression that gets evaluated and the value is returned. If there is
no expression in the statement or the return statement itself is not present inside a function, then the
function will return the None object.

All the above examples are not returning any value. You can return a value from a function as follows −
#!/usr/bin/python

# Function definition is here


def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2
print "Inside the function : ", total
return total;

# Now you can call sum function


total = sum( 10, 20 );
print "Outside the function : ", total
When the above code is executed, it produces the following result −
Inside the function : 30
Outside the function : 30

Ex: def absolute_value(num):


"""This function returns the absolute
value of the entered number"""

if num >= 0:
return num
else:
return -num

print(absolute_value(2))
print(absolute_value(-4))

Output: 2
4
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

Global vs. Local variables


Variables that are defined inside a function body have a local scope, and those defined outside have a
global scope.
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 you call a
function, the variables declared inside it are brought into scope. Following is a simple example −

#!/usr/bin/python

total = 0; # This is global variable.


# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2; # Here total is local variable.
print "Inside the function local total : ", total
return total;

# Now you can call sum function


sum( 10, 20 );
print "Outside the function global total : ", total
When the above code is executed, it produces the following result −
Inside the function local total : 30
Outside the function global total : 0

Types of Functions
Basically, we can divide functions into the following two types:
1. Built-in functions - Functions that are built into Python.
2. User-defined functions - Functions defined by the users themselves.

Python Recursion
What is recursion?
Recursion is the process of defining something in terms of itself.
A physical world example would be to place two parallel mirrors facing each other. Any object in
between them would be reflected recursively.

Python Recursive Function


In Python, we know that a function can call other functions. It is even possible for the function to call
itself. These types of construct are termed as recursive functions.
The following image shows the working of a recursive function called recurse.
Recursive Function in Python
Following is an example of a recursive function to find the factorial of an integer.
Factorial of a number is the product of all the integers from 1 to that number. For example, the factorial of
6 (denoted as 6!) is 1*2*3*4*5*6 = 720.
Example of a recursive function

def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""

if x == 1:
return 1
else:
return (x * factorial(x-1))

num = 3
print("The factorial of", num, "is", factorial(num))

Output

The factorial of 3 is 6

Advantages of Recursion
1. Recursive functions make the code look clean and elegant.
2. A complex task can be broken down into simpler sub-problems using recursion.
3. Sequence generation is easier with recursion than using some nested iteration.

Disadvantages of Recursion
1. Sometimes the logic behind recursion is hard to follow through.
2. Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
3. Recursive functions are hard to debug.
Object Oriented Programming
Python has been an object-oriented language since it existed. Because of this, creating and using classes
and objects are downright easy. This chapter helps you become an expert in using Python's object-
oriented programming support.
If you do not have any previous experience with object-oriented (OO) programming, you may want to
consult an introductory course on it or at least a tutorial of some sort so that you have a grasp of the basic
concepts.
However, here is small introduction of Object-Oriented Programming (OOP) to bring you at speed −

Overview of OOP Terminology


 Class − A user-defined prototype for an object that defines a set of attributes that characterize
any object of the class. The attributes are data members (class variables and instance variables)
and methods, accessed via dot notation.
 Class variable − A variable that is shared by all instances of a class. Class variables are defined
within a class but outside any of the class's methods. Class variables are not used as frequently
as instance variables are.
 Data member − A class variable or instance variable that holds data associated with a class and
its objects.
 Function overloading − The assignment of more than one behavior to a particular function. The
operation performed varies by the types of objects or arguments involved.
 Instance variable − A variable that is defined inside a method and belongs only to the current
instance of a class.
 Inheritance − The transfer of the characteristics of a class to other classes that are derived from
it.
 Instance − An individual object of a certain class. An object obj that belongs to a class Circle,
for example, is an instance of the class Circle.
 Instantiation − The creation of an instance of a class.
 Method − A special kind of function that is defined in a class definition.
 Object − A unique instance of a data structure that's defined by its class. An object comprises
both data members (class variables and instance variables) and methods.
 Operator overloading − The assignment of more than one function to a particular operator.

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
 The class has a documentation string, which can be accessed via ClassName.__doc__.
 The class_suite consists of all the component statements defining class members, data attributes
and functions.

Example

Following is the example of a simple Python class −


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
 The variable empCount is a class variable whose value is shared among all instances of a this
class. This can be accessed as Employee.empCount from inside the class or outside the class.
 The first method __init__() is a special method, which is called class constructor or initialization
method that Python calls when you create a new instance of this class.
 You declare other class methods like normal functions with the exception that the first argument
to each method is self. Python adds the self argument to the list for you; you do not need to
include it when you call the methods.

Creating Instance Objects


To create instances of a class, you call the class using class name and pass in whatever arguments
its __init__ method accepts.
"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)

Accessing Attributes
You 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
Now, putting all the concepts together −
#!/usr/bin/python

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

"This would create first object of Employee class"


emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
When the above code is executed, it produces the following result −
Name : Zara ,Salary: 2000
Name : Manni ,Salary: 5000
Total Employee 2
You can add, remove, or modify attributes of classes and objects at any time −
emp1.age = 7 # Add an 'age' attribute.
emp1.age = 8 # Modify 'age' attribute.
del emp1.age # Delete 'age' attribute.
Instead of using the normal statements to access attributes, you can use the following functions −
 The getattr(obj, name[, default]) − to access the attribute of object.
 The hasattr(obj,name) − to check if an attribute exists or not.
 The setattr(obj,name,value) − to set an attribute. If attribute does not exist, then it would be
created.
 The delattr(obj, name) − to delete an attribute.
hasattr(emp1, 'age') # Returns true if 'age' attribute exists
getattr(emp1, 'age') # Returns value of 'age' attribute
setattr(emp1, 'age', 8) # Set attribute 'age' at 8
delattr(empl, 'age') # Delete attribute 'age'

Built-In Class Attributes


Every Python class keeps following built-in attributes and they can be accessed using dot operator like
any other attribute −
 __dict__ − Dictionary containing the class's namespace.
 __doc__ − Class documentation string or none, if undefined.
 __name__ − Class name.
 __module__ − Module name in which the class is defined. This attribute is "__main__" in
interactive mode.
 __bases__ − A possibly empty tuple containing the base classes, in the order of their occurrence
in the base class list.
For the above class let us try to access all these attributes −
#!/usr/bin/python

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

print "Employee.__doc__:", Employee.__doc__


print "Employee.__name__:", Employee.__name__
print "Employee.__module__:", Employee.__module__
print "Employee.__bases__:", Employee.__bases__
print "Employee.__dict__:", Employee.__dict__
When the above code is executed, it produces the following result −
Employee.__doc__: Common base class for all employees
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: ()
Employee.__dict__: {'__module__': '__main__', 'displayCount':
<function displayCount at 0xb7c84994>, 'empCount': 2,
'displayEmployee': <function displayEmployee at 0xb7c8441c>,
'__doc__': 'Common base class for all employees',
'__init__': <function __init__ at 0xb7c846bc>}

Destroying Objects (Garbage Collection)


Python deletes unneeded objects (built-in types or class instances) automatically to free the memory
space. The process by which Python periodically reclaims blocks of memory that no longer are in use is
termed Garbage Collection.
Python's garbage collector runs during program execution and is triggered when an object's reference
count reaches zero. An object's reference count changes as the number of aliases that point to it changes.
An object's reference count increases when it is assigned a new name or placed in a container (list, tuple,
or dictionary). The object's reference count decreases when it's deleted with del, its reference is
reassigned, or its reference goes out of scope. When an object's reference count reaches zero, Python
collects it automatically.
a = 40 # Create object <40>
b=a # Increase ref. count of <40>
c = [b] # Increase ref. count of <40>

del a # Decrease ref. count of <40>


b = 100 # Decrease ref. count of <40>
c[0] = -1 # Decrease ref. count of <40>
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
When the above code is executed, it produces following result −
3083401324 3083401324 3083401324
Point destroyed
Note − Ideally, you should define your classes in separate file, then you should import them in your
main program file using import statement.

Class Inheritance
Instead of starting from scratch, you 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 you 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 −
class SubClassName (ParentClass1[, ParentClass2, ...]):
'Optional class documentation string'
class_suite

Example

#!/usr/bin/python

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

class Child(Parent): # define child class


def __init__(self):
print "Calling child constructor"
def childMethod(self):
print 'Calling child method'

c = Child() # instance of child


c.childMethod() # child calls its method
c.parentMethod() # calls parent's method
c.setAttr(200) # again call parent's method
c.getAttr() # again call parent's method
When the above code is executed, it produces the following result −
Calling child constructor
Calling child method
Calling parent method
Parent attribute : 200
Similar way, you can drive a class from multiple parent classes as follows −
class A: # define your class A
.....

class B: # define your class B


.....

class C(A, B): # subclass of A and B


.....
You can use issubclass() or isinstance() functions to check a relationships of two classes and instances.
 The issubclass(sub, sup) boolean function returns true if the given subclass sub is indeed a
subclass of the superclass sup.
 The isinstance(obj, Class) boolean function returns true if obj is an instance of class Class or is
an instance of a subclass of Class

Overriding Methods
You can always override your parent class methods. One reason for overriding parent's methods is
because you may want special or different functionality in your subclass.

Example

#!/usr/bin/python

class Parent: # define parent class


def myMethod(self):
print 'Calling parent method'

class Child(Parent): # define child class


def myMethod(self):
print 'Calling child method'

c = Child() # instance of child


c.myMethod() # child calls overridden method
When the above code is executed, it produces the following result −
Calling child method
Base Overloading Methods
Following table lists some generic functionality that you can override in your own classes −

Sr.No. Method, Description & Sample Call

1
__init__ ( self [,args...] )
Constructor (with any optional arguments)
Sample Call : obj = className(args)

2
__del__( self )
Destructor, deletes an object
Sample Call : del obj

3
__repr__( self )
Evaluable string representation
Sample Call : repr(obj)

4
__str__( self )
Printable string representation
Sample Call : str(obj)

5
__cmp__ ( self, x )
Object comparison
Sample Call : cmp(obj, x)

Overloading Operators
Suppose you have created a Vector class to represent two-dimensional vectors, what happens when you
use the plus operator to add them? Most likely Python will yell at you.
You could, however, define the __add__ method in your class to perform vector addition and then the
plus operator would behave as per expectation −

Example

#!/usr/bin/python

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. You need to name attributes
with a double underscore prefix, and those attributes then are not be directly visible to outsiders.

Example

#!/usr/bin/python

class JustCounter:
__secretCount = 0

def count(self):
self.__secretCount += 1
print self.__secretCount

counter = JustCounter()
counter.count()
counter.count()
print counter.__secretCount
When the above code is executed, it produces the following result −
1
2
Traceback (most recent call last):
File "test.py", line 12, in <module>
print counter.__secretCount
AttributeError: JustCounter instance has no attribute '__secretCount'
Python protects those members by internally changing the name to include the class name. You can
access such attributes as object._className__attrName. If you would replace your last line as following,
then it works for you −
.........................
print counter._JustCounter__secretCount
When the above code is executed, it produces the following result −
1
2
2
Advantages and Disadvantages of Object-Oriented Programming (OOP)
This reading discusses advantages and disadvantages of object-oriented programming, which is a
well-adopted programming style that uses interacting objects to model and solve complex programming
tasks. Two examples of popular object-oriented programming languages are Java and C++. Some other
well-known object-oriented programming languages include Objective C, Perl, Python, Javascript,
Simula, Modula, Ada, Smalltalk, and the Common Lisp Object Standard.

Some of the advantages of object-oriented programming include:


1. Improved software-development productivity: Object-oriented programming is modular, as it
provides separation of duties in object-based program development. It is also extensible, as objects can be
extended to include new attributes and behaviors. Objects can also be reused within an across
applications. Because of these three factors – modularity, extensibility, and reusability – object-oriented
programming provides improved software-development productivity over traditional procedure-based
programming techniques.
2. Improved software maintainability: For the reasons mentioned above, objectoriented software is also
easier to maintain. Since the design is modular, part of the system can be updated in case of issues
without a need to make large-scale changes.
3. Faster development: Reuse enables faster development. Object-oriented programming languages
come with rich libraries of objects, and code developed during projects is also reusable in future projects.
4. Lower cost of development: The reuse of software also lowers the cost of development. Typically,
more effort is put into the object-oriented analysis and design, which lowers the overall cost of
development.
5. Higher-quality software: Faster development of software and lower cost of development allows more
time and resources to be used in the verification of the software. Although quality is dependent upon the
experience of the teams, objectoriented programming tends to result in higher-quality software.

Some of the disadvantages of object-oriented programming include:


1. Steep learning curve: The thought process involved in object-oriented programming may not be
natural for some people, and it can take time to get used to it. It is complex to create programs based on
interaction of objects. Some of the key programming techniques, such as inheritance and polymorphism,
can be challenging to comprehend initially.
2. Larger program size: Object-oriented programs typically involve more lines of code than procedural
programs.
3. Slower programs: Object-oriented programs are typically slower than procedurebased programs, as
they typically require more instructions to be executed.
4. Not suitable for all types of problems: There are problems that lend themselves well to functional-
programming style, logic-programming style, or procedure-based programming style, and applying
object-oriented programming in those situations will not result in efficient programs.
Unit – 4 Python

Read and write configuration files using python


There are several file formats you can use for your configuration file, the most commonly used
format are .ini, .json and .yaml.
Read .ini file
Below is a example of the ini file, you can define the sections (e.g. [LOGIN]) as much as you
want to separate the different configuration info.
[LOGIN]
user = admin
#Please change to your real password
password = admin
[SERVER]
host = 192.168.0.1
port = 8088
In python, there is already a module configparser to read and parse the information from the ini
file in to dictionary objects. Assume you have saved above as config.ini file into your current
folder, you can use the below lines of code to read.

import configparser
config = configparser.ConfigParser()
config.read("config.ini")
login = config['LOGIN']
server = config['SERVER']
You can assign each of the sections into a separate dictionary for easier accessing the values. The
output should be same as below:

Note that the line starting with # symbol (or ; ) will be taken as comment line and omitted when
parsing the keys and values.
Also all the values are taken as string, so you will need to do your own data type conversion after
you read it.
Write to .ini file
Now let’s see how we can write to an ini file.
You will still need this configparser library, and the idea is that you need to set the keys and
values into the configparser object and then save it into a file.
config = configparser.ConfigParser()
if not config.has_section("INFO"):
config.add_section("INFO")
config.set("INFO", "link", "www.codeforests.com")
config.set("INFO", "name", "ken") with open("example.ini", 'w') as configfile:
config.write(configfile)
And this would create the example.ini file with below content:
[INFO]
link = www.codeforests.com
name = ken

Reading and Writing to text files in Python


Python provides inbuilt functions for creating, writing and reading files. There are two types of
files that can be handled in python, normal text files and binary files (written in binary language:
0s and 1s).
 Text files: In this type of file, Each line of text is terminated with a special character called
EOL (End of Line), which is the new line character (‘\n’) in python by default.
 Binary files: In this type of file, there is no terminator for a line and the data is stored after
converting it into machine understandable binary language.

File Access Modes


Access modes govern the type of operations possible in the opened file. It refers to how the file
will be used once its opened. These modes also define the location of the File Handle in the file.
File handle is like a cursor, which defines from where the data has to be read or written in the
file. There are 6 access modes in python.
1. Read Only (‘r’) : Open text file for reading. The handle is positioned at the beginning of the
file. If the file does not exists, raises I/O error. This is also the default mode in which file is
opened.
2. Read and Write (‘r+’) : Open the file for reading and writing. The handle is positioned at the
beginning of the file. Raises I/O error if the file does not exists.
3. Write Only (‘w’) : Open the file for writing. For existing file, the data is truncated and over-
written. The handle is positioned at the beginning of the file. Creates the file if the file does
not exists.
4. Write and Read (‘w+’) : Open the file for reading and writing. For existing file, data is
truncated and over-written. The handle is positioned at the beginning of the file.
5. Append Only (‘a’) : Open the file for writing. The file is created if it does not exist. The
handle is positioned at the end of the file. The data being written will be inserted at the end,
after the existing data.
6. Append and Read (‘a+’) : Open the file for reading and writing. The file is created if it does
not exist. The handle is positioned at the end of the file. The data being written will be
inserted at the end, after the existing data.

Opening a File
It is done using the open() function. No module is required to be imported for this function.
File_object = open(r"File_Name","Access_Mode")
The file should exist in the same directory as the python program file else, full address of the file
should be written on place of filename.
Note: The r is placed before filename to prevent the characters in filename string to be treated as
special character. For example, if there is \temp in the file address, then \t is treated as the tab
character and error is raised of invalid address. The r makes the string raw, that is, it tells that the
string is without any special characters. The r can be ignored if the file is in same directory and
address is not being placed.
file1 = open("MyFile.txt","a")
file2 = open(r"D:\Text\MyFile2.txt","w+")
Here, file1 is created as object for MyFile1 and file2 as object for MyFile2
Closing a file
close() function closes the file and frees the memory space acquired by that file. It is used at the
time when the file is no longer needed or if it is to be opened in a different file mode.
File_object.close()

file1 = open("MyFile.txt","a")
file1.close()
Writing to a file
There are two ways to write in a file.

1. write() : Inserts the string str1 in a single line in the text file.
File_object.write(str1)
2. writelines() : For a list of string elements, each string is inserted in the text file.Used to insert
multiple strings at a single time.
File_object.writelines(L) for L = [str1, str2, str3]
Reading from a file
There are three ways to read data from a text file.
1. read() : Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads the
entire file.
File_object.read([n])
2. readline() : Reads a line of the file and returns in form of a string.For specified n, reads at
most n bytes. However, does not reads more than one line, even if n exceeds the length of the
line.
File_object.readline([n])
3. readlines() : Reads all the lines and return them as each line a string element in a list.
File_object.readlines()
Note: ‘\n’ is treated as a special character of two bytes

Examples:
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]
file1.write("Hello \n")
file1.writelines(L)
file1.close()
file1 = open("myfile.txt","r+")
print("Output of Read function is ")
print(file1.read())
# move to start of file again
file1.seek(0)
print("Output of Readline function is ")
print(file1.readline())
# move to start of file again
file1.seek(0)
print("Output of Read(9) function is ")
print(file1.read(9))
# move to start of file again
file1.seek(0)
print("Output of Readline(9) function is ")
print(file1.readline(9))
# move to start of file again
file1.seek(0)
print("Output of Readlines function is ")
print(file1.readlines())
file1.close()
Output:
Output of Read function is
Hello
This is Delhi
This is Paris
This is London

Output of Readline function is


Hello

Output of Read(9) function is


Hello
Th

Output of Readline(9) function is


Hello

Output of Readlines function is


['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']

Appending to a file
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]
file1.close()
# Append-adds at last
file1 = open("myfile.txt","a")#append mode
file1.write("Today \n")
file1.close()

file1 = open("myfile.txt","r")
print("Output of Readlines after appending")
print(file1.readlines())
file1.close()

# Write-Overwrites
file1 = open("myfile.txt","w")#write mode
file1.write("Tomorrow \n")
file1.close()

file1 = open("myfile.txt","r")
print("Output of Readlines after writing")
print(file1.readlines())
file1.close()
Output:
Output of Readlines after appending
['This is Delhi \n', 'This is Paris \n', 'This is London \n', 'Today \n']

Output of Readlines after writing


['Tomorrow \n']

Using write along with with() function


We can also use write function along with with() function:
# Python code to illustrate with() alongwith write()
with open("file.txt", "w") as f:
f.write("Hello World!!!")

Object Oriented Programming


The programs designed around functions i.e. blocks of statements which manipulate data are
called the procedure-oriented way of programming. There is another way of organizing the
program that combine data and functionality and wrap it inside something called an object. This
is called the object oriented programming paradigm. Most of the time we can use procedural
programming, but when writing large programs or have a problem that is better suited to this
method, we can use object oriented programming techniques.
Classes and objects are the two main aspects of object oriented programming. A class creates a
new type where objects are instances of the class.
Objects can store data using ordinary variables that belong to the object. Variables that belong to
an object or class are referred to as fields. Objects can also have functionality by using functions
that belong to a class. Such functions are called methods of the class. Fields are of two types -
they can belong to each instance/object of the class or they can belong to the class itself. They
are called instance variables and class variables respectively.
A class is created using the class keyword. The fields and methods of the class are listed in an
indented block.

The self
Class methods have only one specific difference from ordinary functions - they must have an
extra first name that has to be added to the beginning of the parameter list, but you do not give a
value for this parameter when you call the method, Python will provide it. This particular
variable refers to the object itself, and by convention, it is given the name self.
Although, you can give any name for this parameter, it is strongly recommended that you use the
name self.
The self in Python is equivalent to the this pointer in C++ and the this reference in Java and C#.
If you have a method which takes no arguments, then you still have to have one argument -
the self.

Classes
The simplest class possible is shown in the following example (save as oop_simplestclass.py).
class Person:
pass # An empty block

p = Person()
print(p)
Output:
$ python oop_simplestclass.py
<__main__.Person instance at 0x10171f518>
Notice that the address of the computer memory where your object is stored is also printed. The
address will have a different value on your computer since Python can store the object wherever
it finds space.

Methods
Classes/objects can have methods just like functions except that we have an extra self variable.
We will now see an example (save as oop_method.py).
class Person:
def say_hi(self):
print('Hello, how are you?')

p = Person()
p.say_hi()
Output:
$ python oop_method.py
Hello, how are you?

The __init__ method


The __init__ method is run as soon as an object of a class is instantiated (i.e. created). The
method is useful to do any initialization (i.e. passing initial values to your object) you want to do
with your object. Notice the double underscores both at the beginning and at the end of the name.
Example (save as oop_init.py):
class Person:
def __init__(self, name):
self.name = name

def say_hi(self):
print('Hello, my name is', self.name)

p = Person('Swaroop')
p.say_hi()
Output:
$ python oop_init.py
Hello, my name is Swaroop

Class variables And Instance Variables


The data part, i.e. fields, are nothing but ordinary variables that are bound to the namespaces of
the classes and objects. This means that these names are valid within the context of these classes
and objects only. That's why they are called name spaces.
There are two types of fields - class variables and object variables(instance variables) which are
classified depending on whether the class or the object owns the variables respectively.
Class variables are shared - they can be accessed by all instances of that class. There is only one
copy of the class variable and when any one object makes a change to a class variable, that
change will be seen by all the other instances.
Object variables are owned by each individual object/instance of the class. In this case, each
object has its own copy of the field i.e. they are not shared and are not related in any way to the
field by the same name in a different instance. An example will make this easy to understand
(save as oop_objvar.py):
class Robot:
# A class variable, counting the number of robots
population = 0

def __init__(self, name):


self.name = name
Robot.population += 1

def die(self):
print("{} is being destroyed!".format(self.name))
Robot.population -= 1

if Robot.population == 0:
print("{} was the last one.".format(self.name))
else:
print("There are still {:d} robots working.".format(Robot.population))
def say_hi(self):
print("Greetings, my masters call me {}.".format(self.name))

@classmethod
def how_many(cls):
"""Prints the current population."""
print("We have {:d} robots.".format(cls.population))

droid1 = Robot("R2-D2")
droid1.say_hi()
Robot.how_many()

droid2 = Robot("C-3PO")
droid2.say_hi()
Robot.how_many()

print("\nRobots can do some work here.\n")

print("Robots have finished their work. So let's destroy them.")


droid1.die()
droid2.die()

Robot.how_many()
Output:
$ python oop_objvar.py
Greetings, my masters call me R2-D2.
We have 1 robots.
Greetings, my masters call me C-3PO.
We have 2 robots.

Robots can do some work here.

Robots have finished their work. So let's destroy them.


R2-D2 is being destroyed!
There are still 1 robots working.
C-3PO is being destroyed!
C-3PO was the last one.
We have 0 robots.

Inheritance
One of the major benefits of object oriented programming is reuse of code and one of the ways
this is achieved is through the inheritance mechanism. Inheritance can be best imagined as
implementing a type and subtype relationship between classes.
To make a class inherit from another, we apply the name of the base class in parentheses to the
derived class’ definition.
class Person:
pass
class Student(Person):
pass
here, student is a subclass of person.

We will now see this example as a program (save as oop_subclass.py):


class SchoolMember:
def __init__(self, name, age):
self.name = name
self.age = age
def tell(self):
print('Name:"{}" Age:"{}"'.format(self.name, self.age), end=" ")

class Teacher(SchoolMember):
def __init__(self, name, age, salary):
SchoolMember.__init__(self, name, age)
self.salary = salary

def tell(self):
SchoolMember.tell(self)
print('Salary: "{:d}"'.format(self.salary))

class Student(SchoolMember):
'''Represents a student.'''
def __init__(self, name, age, marks):
SchoolMember.__init__(self, name, age)
self.marks = marks

def tell(self):
SchoolMember.tell(self)
print('Marks: "{:d}"'.format(self.marks))

t = Teacher('Mrs. Shrividya', 40, 30000)


s = Student('Swaroop', 25, 75)

# prints a blank line


print()

members = [t, s]
for member in members:
# Works for both Teachers and Students
member.tell()
Output:
$ python oop_subclass.py
Name:"Mrs. Shrividya" Age:"40" Salary: "30000"
Name:"Swaroop" Age:"25" Marks: "75"

Types of Inheritance in Python


There are five types of inheritance in python.
a. Single Inheritance
A single inheritance is when a single class inherits from a class.
class fruit:
def __init__(self):
print("I'm a fruit")
class citrus(fruit):
def __init__(self):
super().__init__()
print("I'm citrus")

lime=citrus()
I’m a fruit
I’m citrus
b. Multiple Inheritance
Multiple inheritance are when a class inherits from multiple base classes.
class Color:
pass
class Fruit:
pass
class Orange(Color,Fruit):
pass
c. Multilevel Inheritance
When one class inherits from another, which in turn inherits from another, it is multilevel python
inheritance.
class A:
x=1
class B(A):
pass
class C(B):
pass
cobj=C()
cobj.x
1
d. Hierarchical Inheritance
When more than one class inherits from a class, it is hierarchical Python inheritance.
class A:
pass
class B(A):
pass
class C(A):
pass
e. Hybrid Inheritance
Hybrid Python inheritance is a combination of any two or more kinds of inheritance.
class A:
x=1
class B(A):
pass
class C(A):
pass
class D(B,C):
pass
dobj=D()
dobj.x
1

Method Overriding
A subclass may change the functionality of a Python method in the superclass. It does so by
redefining it. This is termed python method overriding. Lets see this Python Method Overriding
Example.
class A:
def sayhi(self):
print("I'm in A")
class B(A):
def sayhi(self):
print("I'm in B")
bobj=B()
bobj.sayhi()
output:
I’m in B

Data Hiding
Data hiding is one of the important features of Object Oriented Programming which allows
preventing the functions of a program to access directly the internal representation of a class
type. By default all members of a class can be accessed outside of class.
You can prevent this by making class members private or protected.
In Python, we use double underscore (__) before the attributes name to make those
attributes private.
We can use single underscore (_) before the attributes name to make those attributes protected.
class MyClass:
__hiddenVariable = 0 # Private member of MyClass
_protectedVar = 0 # Protected member of MyClass

# A member method that changes __hiddenVariable


def add(self, increment):
self.__hiddenVariable += increment
print (self.__hiddenVariable)

myObject = MyClass()
myObject.add(2)
myObject.add(5)

# This will causes error


print (MyClass.__hiddenVariable)
print (MyClass._protectedVar)
In the above program, we tried to access hidden variable outside the class using object and it
threw an exception.
We can access the value of hidden attribute by a tricky syntax
as object._className__attrName.

# A Python program to demonstrate that hidden members can be accessed outside a class
class MyClass:
__hiddenVariable = 10 # Hidden member of MyClass

myObject = MyClass()
print(myObject._MyClass__hiddenVariable)
Private methods are accessible outside their class, just not easily accessible. Nothing in Python is
truly private.

Difference between public, private and protected:


Mode Description
Public A public member is accessible from anywhere outside the class but
within a program. You can set and get the value of public variables
without any member function. By default all the members of a class
would be public
Private A private member variable or function cannot be accessed, or even
viewed from outside the class. Only the class members can access
private members. Practically, we make data private and related
functions public so that they can be called from outside of the class
Protected A protected member is very similar to a private member but it
provided one additional benefit that they can be accessed in sub
classes which are called derived/child classes.

Python Operator Overloading


You can change the meaning of an operator in Python depending upon the operands used.
Python operators work for built-in classes. But the same operator behaves differently with
different types. For example, the + operator will perform arithmetic addition on two numbers,
merge two lists, or concatenate two strings.
This feature in Python that allows the same operator to have different meaning according to the
context is called operator overloading.
So what happens when we use them with objects of a user-defined class? Let us consider the
following class, which tries to simulate a point in 2-D coordinate system.

class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y

p1 = Point(1, 2)
p2 = Point(2, 3)
print(p1+p2)

Output

Traceback (most recent call last):


File "<string>", line 9, in <module>
print(p1+p2)
TypeError: unsupported operand type(s) for +: 'Point' and 'Point'

Here, we can see that a TypeError was raised, since Python didn't know how to add
two Point objects together.

Python Special Functions


Suppose we want the print() function to print the coordinates of the Point object instead of what
we got. We can define a __str__() method in our class that controls how the object gets printed.
Let's look at how we can achieve this:

class Point:
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y

def __str__(self):
return "({0},{1})".format(self.x,self.y)

Now let's try the print() function again.

class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y

def __str__(self):
return "({0}, {1})".format(self.x, self.y)
p1 = Point(2, 3)
print(p1)

Output

(2, 3)

Overloading the + Operator


To overload the + operator, we will need to implement __add__() function in the class. With
great power comes great responsibility. We can do whatever we like, inside this function. But it
is more sensible to return a Point object of the coordinate sum.

class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y

def __str__(self):
return "({0},{1})".format(self.x, self.y)

def __add__(self, other):


x = self.x + other.x
y = self.y + other.y
return Point(x, y)

Now let's try the addition operation again:

class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y

def __str__(self):
return "({0},{1})".format(self.x, self.y)

def __add__(self, other):


x = self.x + other.x
y = self.y + other.y
return Point(x, y)

p1 = Point(1, 2)
p2 = Point(2, 3)
print(p1+p2)

Output

(3,5)

What actually happens is that, when you use p1 + p2, Python calls p1.__add__(p2) which in turn
is Point.__add__(p1,p2). After this, the addition operation is carried out the way we specified.
Similarly, we can overload other operators as well. The special function that we need to
implement is tabulated below.
Operator Expression Internally

Addition p1 + p2 p1.__add__(p2)

Subtraction p1 - p2 p1.__sub__(p2)

Multiplication p1 * p2 p1.__mul__(p2)

Power p1 ** p2 p1.__pow__(p2)

Division p1 / p2 p1.__truediv__(p2)

Floor Division p1 // p2 p1.__floordiv__(p2)

Remainder (modulo) p1 % p2 p1.__mod__(p2)

Bitwise Left Shift p1 << p2 p1.__lshift__(p2)

Bitwise Right Shift p1 >> p2 p1.__rshift__(p2)

Bitwise AND p1 & p2 p1.__and__(p2)

Bitwise OR p1 | p2 p1.__or__(p2)

Bitwise XOR p1 ^ p2 p1.__xor__(p2)

Bitwise NOT ~p1 p1.__invert__()


Overloading Comparison Operators
Python does not limit operator overloading to arithmetic operators only. We can overload
comparison operators as well.
Suppose we wanted to implement the less than symbol < symbol in our Point class.
Let us compare the magnitude of these points from the origin and return the result for this
purpose. It can be implemented as follows.

# overloading the less than operator


class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y

def __str__(self):
return "({0},{1})".format(self.x, self.y)

def __lt__(self, other):


self_mag = (self.x ** 2) + (self.y ** 2)
other_mag = (other.x ** 2) + (other.y ** 2)
return self_mag < other_mag

p1 = Point(1,1)
p2 = Point(-2,-3)
p3 = Point(1,-1)

# use less than


print(p1<p2)
print(p2<p3)
print(p1<p3)

Output

True
False
False

Similarly, the special functions that we need to implement, to overload other comparison
operators are tabulated below.
Operator Expression Internally

Less than p1 < p2 p1.__lt__(p2)

Less than or equal to p1 <= p2 p1.__le__(p2)

Equal to p1 == p2 p1.__eq__(p2)

Not equal to p1 != p2 p1.__ne__(p2)

Greater than p1 > p2 p1.__gt__(p2)

Greater than or equal to p1 >= p2 p1.__ge__(p2)

You might also like