R20-N-Python Unit 4 - Chandu
R20-N-Python Unit 4 - Chandu
PYTHON PROGRAMMING
UNIT –IV
File Operations: Reading config files in python, Writing log files in python, Understanding
read functions, read(), readline() and readlines(), Understanding write functions, write() and
writelines(), Manipulating file pointer using seek, Programming using file operations
Object Oriented Programming: Concept of class, object and instances, Constructor, class
attributes and destructors, Real time use of class in live projects, Inheritance , overlapping and
overloading operators, Adding and retrieving dynamic attributes of classes, Programming
using Oops support
Design with Classes: Objects and Classes, Data modeling Examples, Case Study An ATM,
Structuring Classes with Inheritance and Polymorphism.
File Operations :
A file is a collection of records. A record is a group of related data items.
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.
The config parser module from Python's standard library defines functionality for reading and writing
configuration files as used by Microsoft Windows OS. Such files usually have .INI extension.
The INI file consists of sections, each led by a [section] header. Between square brackets, we can put the
section’s name. Section is followed by key/value entries separated by = or : character. It may include
comments, prefixed by # or ; symbol. A sample INI file is shown below −
[Settings]
# Set detailed log for additional debugging info
DetailedLog=1
RunStatus=1
StatusPort=6090
StatusRefresh=10
Archive=1
# Sets the location of the MV_FTP log file
LogFile=/opt/ecs/mvuser/MV_IPTel/log/MV_IPTel.log
Version=0.9 Build 4
ServerName=Unknown
[FTP]
# set the FTP server active
RunFTP=1
# defines the FTP control port
FTPPort=21
# Sets the location of the FTP data directory
FTPDir=/opt/ecs/mvuser/MV_IPTel/data/FTPdata
# set the admin Name
UserName=admin
# set the Password
Password=admin
The configparser module has ConfigParser class. It is responsible for parsing a list of configuration files,
and managing the parsed database.
Object of ConfigParser is created by following statement −
parser = configparser.ConfigParser()
Following methods are defined in this class −
read_file() Read and parse one configuration file, given as a file object.
getboolean() Like get(), but convert value to a boolean. Returns False or True.
items() return a list of tuples with (name, value) for each option in the
section.
remove_section() Remove the given file section and all its options.
import configparser
parser = configparser.ConfigParser()
parser.read('sampleconfig.ini')
for sect in parser.sections():
print('Section:', sect)
for k,v in parser.items(sect):
print(' {} = {}'.format(k,v))
print()
Output
Section: Settings
detailedlog = 1
runstatus = 1
statusport = 6090
statusrefresh = 10
archive = 1
logfile = /opt/ecs/mvuser/MV_IPTel/log/MV_IPTel.log
version = 0.9 Build 4
servername = Unknown
Section: FTP
runftp = 1
ftpport = 21
ftpdir = /opt/ecs/mvuser/MV_IPTel/data/FTPdata
username = admin
password = admin
The write() method is used to create a configuration file. Following script configures the parser object
and writes it to a file object representing 'test.ini'
import configparser
parser = configparser.ConfigParser()
parser.add_section('Manager')
parser.set('Manager', 'Name', 'Ashok Kulkarni')
parser.set('Manager', 'email', '[email protected]')
parser.set('Manager', 'password', 'secret')
fp=open('test.ini','w')
parser.write(fp)
fp.close()
Python - Print Logs in a File
If you want to print python logs in a file rather than on the console then we can do so using
the basicConfig() method by providing filename and filemode as parameter.The format of the
message can be specified by using format parameter in basicConfig() method.
In the above code, the filemode is set to w, which means the log file is opened in “write mode” each
time basicConfig() is called, and after each run of the program, it will rewrite the file.
The default configuration for filemode is a, that is append, which means that logs will be appended to
the log file and adding logs to the existing logs.
There are some basic steps and these are given below:
1. First of all, simply import the logging module just by writing import logging.
2. The second step is to create and configure the logger. To configure logger to store logs in a file,
it is mandatory to pass the name of the file in which you want to record the events.
3. In the third step, the format of the logger can also be set. Note that by default, the file works
in append mode but we can change that to write mode if required.
4. You can also set the level of the logger.
import logging
logger=logging.getLogger()
logger.setLevel(logging.DEBUG)
logger.warning("OOPS!!!Its a Warning")
The above code will write some messages to file named std.log. If we will open the file then the
messages will be written as follows:
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.
The r can be ignored if the file is in same directory and address is not being placed.
While specifying the exact path, characters prefaced by \ (like \n \r \t etc.) are interpreted as special
characters. You can escape them using:
raw strings like r'C:\new\text.txt'
double backslashes like 'C:\\new\\text.txt'
# Open function to open the file "MyFile1.txt"
# (same directory) in append mode and
file1 = open("MyFile1.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()
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
With Statement
You can also work with file objects using the with statement. It is designed to provide much cleaner
syntax and exceptions handling when you are working with code. That explains why it’s good practice
to use the with statement where applicable.
file1.seek(0)
print ("Output of Readline(9) function is ")
print (file1.readline(9))
file1.seek(0)
# readlines function
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
# Python program to illustrate
file1 = open("myfile.txt","w")
file1.close()
# Append-adds at last
file1.write("Today \n")
file1.close()
file1 = open("myfile.txt","r")
print (file1.readlines())
file1.close()
# Write-Overwrites
file1.write("Tomorrow \n")
file1.close()
file1 = open("myfile.txt","r")
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']
seek() method
In Python, seek() function is used to change the position of the File Handle to a given specific position.
File handle is like a cursor, which defines from where the data has to be read or written in the file.
The reference point is selected by the from_what argument. It accepts three values:
0: sets the reference point at the beginning of the file
1: sets the reference point at the current file position
2: sets the reference point at the end of the file
Example 1: Let’s suppose we have to read a file named “GfG.txt” which contains the following
text:
"Code is like humor. When you have to explain it, it’s bad."
Example 2: Seek() function with negative offset only works when file is opened in binary mode.
Let’s suppose the binary file contains the following text.
b'Code is like humor. When you have to explain it, its bad.'
Class
Object
Method
Inheritance
Polymorphism
Data Abstraction
Encapsulation
Object
An object (instance) is an instantiation of a class. When class is defined, only the description
for the object is defined. Therefore, no memory or storage is allocated
The object is an entity that has state and behavior. It may be any real-world object like the
mouse, keyboard, chair, table, pen, etc.
Everything in Python is an object. All functions have a built-in attribute __doc__, which
returns the docstring defined in the function source code..
For example, a car can be an object. If we consider the car as an object then its properties
would be – its color, its model, its price, its brand, etc. And its behavior/function would be
acceleration, slowing down, gear change.
Another example- If we consider a dog as an object then its properties would be- his color, his
breed, his name, his weight, etc. And his behavior/function would be walking, barking,
playing, etc.
Class
The class can be defined as a collection of objects. It is a logical entity that has some specific
attributes and methods.
The attributes are data members (class variables and instance variables) and methods,
accessed via dot notation.
A class is a blueprint for the object
For example: if you have an employee class, then it should contain an attribute and method,
i.e. an email id, name, age, salary, etc..
class Parrot:
pass
Here, we use the class keyword to define an empty class Parrot. From class, we construct instances. An
instance is a specific object created from a particular class.
Method
Methods are functions defined inside the body of a class. They are used to define the
behaviors of an object.
The method is a function that is associated with an object.
Ex:
def method1 (self):
print "Guru99"
The self-argument refers to the object itself. Hence the use of the word self. So inside this
method, self will refer to the specific instance of this object that's being operated on.
Inheritance
Inheritance is the most important aspect of object-oriented programming, which simulates the
real-world concept of inheritance. It specifies that the child object acquires all the properties
and behaviors of the parent object.
By using inheritance, we can create a class which uses all the properties and behavior of
another class. The new class is known as a derived class or child class, and the one whose
properties are acquired is known as a base class or parent class.
It provides the re-usability of the code.
Polymorphism
Polymorphism is taken from the Greek words Poly (many) and morphism (forms). It means
that the same function name can be used for different types..
By polymorphism, we understand that one task can be performed in different ways.
For example - you have a class animal, and all animals speak. But they speak differently.
Here, the "speak" behavior is polymorphic in a sense and depends on the animal. So, the
abstract "animal" concept does not actually "speak", but specific animals (like dogs and cats)
have a concrete implementation of the action "speak".
Encapsulation
Binding of data and methods into a single unit is called encapsulation. Encapsulation is
accomplished when each object inside the class keeps its state private. The data inside this unit
is not accessible by outside objects and only those functions inside this unit are able to access
it. Thus, the object manages its state with the help of its methods, and to communicate with
this object, we will require the help of the public methods of this class.
Encapsulation is also an essential aspect of object-oriented programming. It is used to restrict
access to methods and variables. In encapsulation, is a process of binding data members and
member functions into a single unit, where data members are variables or properties and
member functions are methods.
Data Abstraction
Abstraction is an extension of encapsulation. It means providing only the necessary
information to the outside world while hiding the internal details of implementation. It reveals
only the appropriate operations for other objects. The advantage of this is that we can change
the implementation without affecting the class, as the method interface remains the same.
.We use Abstraction for hiding the internal details or implementations of a function and
showing its functionalities only. This is similar to the way you know how to drive a car
without knowing the background mechanism. Or you know how to turn on or off a light using
a switch but you don’t know what is happening behind the socket.
Difference between Object-Oriented and Procedural Oriented Programming
Object-Oriented Programming (OOP) Procedural-Oriented Programming (Pop)
It is a bottom-up approach It is a top-down approach
Program is divided into objects Program is divided into functions
Makes use of Access modifiers
Doesn’t use Access modifiers
‘public’, private’, protected’
It is more secure It is less secure
Object-oriented uses objects, classes, messages Procedural uses procedures, modules, procedure calls.
It is easy to maintain. It is not easy to maintain.
Data can move freely from function to function within
Object can move freely within member functions
programs
It supports inheritance It does not support inheritance
Data hiding is possible, hence more secure than
Data hiding is not possible.
procedural.
In OOP, operator overloading is allowed. Operator overloading is not allowed.
Python Class
class <ClassName>:
<statement1>
<statement2> .
.
<statementN>
As per the syntax above, a class is defined using the class keyword followed by the class name
and : operator after the class name, which allows you to continue in the next indented line to define
class members.
The first string inside the class is called docstring and has a brief description of the class. Although not
mandatory, this is highly recommended.
Here is a simple class definition.
class MyNewClass:
'''This is a docstring. I have created a new class'''
pass
A class creates a new local namespace where all its attributes are defined. Attributes may be data or
functions.
There are also special attributes in it that begins with double underscores __. For example, __doc__
gives us the docstring of that class.
As soon as we define a class, a new class object is created with the same name. This class object allows
us to access the different attributes as well as to instantiate new objects of that class.
class Person:
"This is a person class"
age = 10
def greet(self):
print('Hello')
print(Person.age)
print(Person.greet)
print(Person.__doc__)
Output
10
<function Person.greet at 0x7fc78c6e8160>
This is a person class
A class can also be defined without any members. The following example defines an empty class
using the pass keyword.
Example: Define Python Class
class Student:
pass
Creating an Object in Python
We saw that the class object could be used to access different attributes.
It can also be used to create new object instances (instantiation) of that class. The procedure to create an
object is similar to a function call.
>>> harry = Person()
This will create a new object instance named harry. We can access the attributes of objects using the
object name prefix.
Attributes may be data or method. Methods of an object are corresponding functions of that class.
This means to say, since Person.greet is a function object (attribute of class), Person.greet will be a
method object.
class Person:
"This is a person class"
age = 10
def greet(self):
print('Hello')
# create a new object of Person class
harry = Person()
print(Person.greet)
print(harry.greet)
# Calling object's greet() method
# Output: Hello
harry.greet()
Output
<function Person.greet at 0x7fd288e4e160>
<bound method Person.greet of <__main__.Person object at 0x7fd288e9fa30>>
Hello
You may have noticed the self parameter in function definition inside the class but we called the method
simply as harry.greet() without any arguments. It still worked.
Class Attributes
Class attributes are the defined directly in the class that are shared by all objects of the class. Class
attributes can be accessed using the class name as well as using the objects.
Above, the schoolName is a class attribute defined inside a class. The value of the schoolName will
remain the same for all the objects unless modified explicitly.
Constructor
In Python, the constructor method is invoked automatically whenever a new object of a class is
instantiated, same as constructors in C# or Java. The constructor must have a special
name __init__() and a special parameter called self.
The first parameter of each method in a class must be the self , which refers to the calling object.
However, you can give any name to the first parameter, not necessarily self.
Example: Constructor
class Student:
def __init__(self): # constructor method
print('Constructor invoked')
Now, whenever you create an object of the Student class, the __init__() constructor method will be
called, as shown below.
>>>s1 = Student()
Constructor invoked
>>>s2 = Student()
Constructor invoked
The constructor in Python is used to define the attributes of an instance and assign values to them.
Instance Attributes
Instance attributes are attributes or properties attached to an instance of a class. Instance attributes are
defined in the constructor.
The following example defines instance attributes name and age in the constructor.
An instance attribute can be accessed using dot notation: [instance name].[attribute name], as shown
below.
Example:
You can set the value of attributes using the dot notation, as shown below.
Example:
>>> std = Student()
>>> std.name = "Bill" # assign value to instance attribute
>>> std.age=25 # assign value to instance attribute
>>> std.name # access instance attribute value
Bill
>>> std.age # access value to instance attribute
25
You can specify the values of instance attributes through the constructor. The following constructor
includes the name and age parameters, other than the self parameter.
Now, you can specify the values while creating an instance, as shown below.
You don't have to specify the value of the self parameter. It will be assigned internally in Python.
You can also set default values to the instance attributes. The following code sets the default values
of the constructor parameters. So, if the values are not provided when creating an object, the values
will be assigned latter.
class Student:
def __init__(self, name="Guest", age=25)
self.name=name
self.age=age
Class Properties
In Python, a property in the class can be defined using the property() function.
The property() method takes the get, set and delete methods as arguments and returns an object of
the property class.
Example: property()
class Student:
def __init__(self):
self.__name=''
def setname(self, name):
print('setname() called')
self.__name=name
def getname(self):
print('getname() called')
return self.__name
name=property(getname, setname)
In the above example, property(getname, setname) returns the property object and assigns it to name.
Thus, the name property hides the private instance attribute __name. The name property is accessed
directly, but internally it will invoke the getname() or setname() method, as shown below.
Example: property()
>>> std = Student()
>>> std.name="Steve"
setname() called
>>> std.name
getname() called
'Steve'
Class Methods
You can define as many methods as you want in a class using the def keyword. Each method must
have the first parameter, generally named as self, which refers to the calling instance.
Self is just a conventional name for the first argument of a method in the class. A method defined
as mymethod(self, a, b) should be called as x.mymethod(a, b) for the object x of the class.
The above class method can be called as a normal function, as shown below.
The first parameter of the method need not be named self. You can give any name that refers to the
instance of the calling method. The following displayInfo() method names the first parameter
as obj instead of self and that works perfectly fine.
Defining a method in the class without the self parameter would raise an exception when calling a
method.
The method can access instance attributes using the self parameter.
You can delete attributes, objects, or the class itself, using the del keyword, as shown below.
Destructors
Destructors are called when an object gets destroyed. In Python, destructors are not needed as much
needed in C++ because Python has a garbage collector that handles memory management automatically.
The __del__() method is a known as a destructor method in Python. It is called when all references to
the object have been deleted i.e when an object is garbage collected.
def __del__(self):
# body of destructor
Note : A reference to objects is also deleted when the object goes out of reference or when the program
ends.
Example 1 : Here is the simple example of destructor. By using del keyword we deleted the all
references of object ‘obj’, therefore destructor invoked automatically.
# Initializing
def __init__(self):
print('Employee created.')
obj = Employee()
del obj
Output:
Employee created.
Destructor called, Employee deleted.
Note : The destructor was called after the program ended or when all the references to object are deleted
i.e when the reference count becomes zero, not when object went out of scope.
Example 2 :This example gives the explanation of above mentioned note. Here, notice that the
destructor is called after the ‘Program End…’ printed.
class Employee:
# Initializing
def __init__(self):
print('Employee created')
# Calling destructor
def __del__(self):
print("Destructor called")
def Create_obj():
print('Making Object...')
obj = Employee()
print('function end...')
return obj
when working on data science projects or any Python programming project, you will most likely find
yourself utilizing plenty of self-made functions and variables. You may have even create an entire script
filled with functions you created in order to streamline the process of your project.
The purpose of these functions can be for numerous things within your code. From cleaning your
DataFrame to training a machine learning model. It’s useful to create a ton of functions in order to
organize your Python code but there is another way to make your code look and act more presentable —
A Python class is like an outline for creating a new object. An object is anything that you wish to
manipulate or change while working through the code. Every time a class object is instantiated, which is
when we declare a variable, a new object is initiated from scratch. Class objects can be used over and
This data preprocessing step is achieved through the use of numerous functions. It is not organized in the
best way but it gets the job done. However, we can improve the process by utilizing a Python Class.
In order to learn more about class objects and utilizing them, we will be implementing a class object for
our AI Dating Algorithm. Let’s organize and clean up the code we used into a Class object.
First, we must ask ourselves — What do we want this class object to do? We want it to:
3. Scale or vectorize that profile in order for it to be machine learning model friendly.
Basically, we will want it to condense the entire data preprocessing step into a Class object which we can
then use for every new dating profile we wish to add. We can use this class object whenever we need to
Constructing a Class
Within the class, tab over to start defining our first function. Usually, when creating a class, you will have
An __init__ function is called when a class is instantiated. By instantiate, we mean when you declare the
class, which can happen either by itself or by assigning it to a variable. Here are some quick examples of
Here we are instantiating the class object and by doing so, we are implicitly calling the __init__ function.
Any arguments within the __init__ function will also be the same arguments when instantiating the class
object. These initial arguments can be the data we wish to manipulate throughout the class object. But in
regards to the self argument, it will not be necessary to replace when instantiating the class object.
Python Inheritance
Inheritance is the process of creating a new Class, called the Derived Class , from the existing
class, called the Base Class .
When a new class inherits from an existing one, the existing one is called the parent
class(super-class) and the new class is called the child class(sub-class).
Inheritance allows us to define a class that inherits all the methods and properties from another
class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived class.
It represents real-world relationships well.
It provides reusability of a code. We don’t have to write the same code again and again. Also, it
allows us to add more features to a class without modifying it.
It offers faster development time, easier maintenance and easy to extend.
Any class can be a parent class, so the syntax is the same as creating any other class:
Example
Create a class named Person, with firstname and lastname properties, and a printname method:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
#Use the Person class to create an object, and then execute the printname method:
x = Person("John", "Doe")
x.printname()
Create a Child Class
To create a class that inherits the functionality from another class, send the parent class as a parameter
when creating the child class:
Example
Create a class named Student, which will inherit the properties and methods from the Person class:
Note: Use the pass keyword when you do not want to add any other properties or methods to the class.
class Student(Person):
pass
x = Student("Mike", "Olsen")
x.printname()
Example2:
parentAttr = 100
def __init__(self):
def parentMethod(self):
def __init__(self):
def childMethod(self):
Output
Single Inheritance
Multi Level Inheritance
Multipath inheritance
Multiple Inheritance
Hierarchical Inheritance
Hybrid Inheritance
Single Inheritence:
When a Derived Class to inherit properties and behavior from a single Base Class , it is called as single
inheritance.
Example:
# Single inheritence
class Apple:
manufacturer = 'Apple Inc'
contact_website = 'www.apple.com/contact'
name = 'Apple'
def contact_details(self):
print('Contact us at ', self.contact_website)
class MacBook(Apple):
def __init__(self):
self.year_of_manufacture = 2018
def manufacture_details(self):
print('This MacBook was manufactured in {0}, by {1}.'
.format(self.year_of_manufacture, self.manufacturer))
macbook = MacBook()
macbook.manufacture_details()
output:
This MacBook was manufactured in 2018, by Apple Inc.
Multiple inheritance
In multiple inheritance one child class can inherit multiple parent classes.
def show_father(self):
print(self.fathername)
mothername = ""
def show_mother(self):
print(self.mothername)
A derived class is created from another derived class is called Multi Level Inheritance .
In this type of inheritance, a class can inherit from a child class or derived class.
Here each class only inherits once, at most, but they inherit as a series.
Example:
class Family:
def show_family(self):
print("This is our family:")
# Father class inherited from Family
class Father(Family):
fathername = ""
def show_father(self):
print(self.fathername)
# Mother class inherited from Family
class Mother(Family):
mothername = ""
def show_mother(self):
print(self.mothername)
# Son class inherited from Father and Mother classes
class Son(Father, Mother):
def show_parent(self):
print("Father :", self.fathername)
print("Mother :", self.mothername)
s1 = Son() # Object of Son class
s1.fathername = "Mark"
s1.mothername = "Sonia"
s1.show_family()
s1.show_parent()
Output:
This is our family:
Father : Mark
Mother : Sonia
Multipath inheritance
Multiple inheritance is a method of inheritance in which one derived class can inherit properties of base
class in different paths.
Multipath inheritance is a two level inheritance. Derived class in a Multipath Inheritance inherits the
properties of two or more parents classes and their parents classes inherits the properties from single
base class.
The multipath inheritance is a combination of multi level and multiple inheritances. Thus, in this type of
inheritance, the public properties of base class are derived into various sub classes. All the public
properties of sub classes are further derived into the final sub class. The multi path inheritance is shown
in Fig. 10.7. The syntax of the multiple inheritance is given below
class base_class1
class sub_class1(base_class1):
#body of subclass1
class sub_class2(base_class1):
class b(a):
y=200
class c(a):
z=300
class d(b,c):
p=500
def f1(self):
print("Properties of sub class: ",self.x,self.y,self.z,self.p)
obj1=d()
obj1.f1()
Output:
D:\PythonPrograms>python b2.py Properties of
sub class: 100 200 300 500
Operator Overloading means giving extended meaning beyond their predefined operational meaning.
For example operator + is used to add two integers as well as join two strings and merge two lists. It is
achievable because ‘+’ operator is overloaded by int class and str class. You might have noticed that the
same built-in operator or function shows different behavior for objects of different classes, this is
called Operator Overloading.
3
LearnFor
12
LearnLearnLearnLearn
Operator overloading is nothing but same name but differerent type of arguments or return type
Ex:print(1*7)
print(“hii"+”hello”)
Overlapping means ex:the elements of tuple1 is at least one element equal to tuple2
Ex:q=(1,2,7)
W=(1,9,7)
in operator : The ‘in’ operator is used to check if a value exists in a sequence or not. Evaluates to true if
it finds a variable in the specified sequence and false otherwise.
# Python program to illustrate
# Finding common member in list
# using 'in' operator
list_1=[1,2,3,4,5]
list2=[6,7,8,9]
for item in list_1:
if item in list2:
print("overlapping")
else:
print("not overlapping")
Output:
not overlapping
Operator Overloading means giving extended meaning beyond their predefined operational
meaning. For example operator + is used to add two integers as well as join two strings and merge two
lists. It is achievable because ‘+’ operator is overloaded by int class and str class. You might have
noticed that the same built-in operator or function shows different behavior for objects of different
classes, this is called Operator Overloading.
print(1 + 2)
Output:
3
GeeksFor
12
GeeksGeeksGeeksGeeks
To perform operator overloading, Python provides some special function or magic function that is
automatically invoked when it is associated with that particular operator. For example, when we use +
operator, the magic method __add__ is automatically invoked in which the operation for + operator is
defined.
Overloading binary + operator in Python :
When we use an operator on user defined data types then automatically a special function or magic
function associated with that operator is invoked. Changing the behavior of operator is as simple as
changing the behavior of method or function. You define methods in your class and operators work
according to that behavior defined in methods. When we use + operator, the magic method __add__ is
automatically invoked in which the operation for + operator is defined. There by changing this magic
method’s code, we can give extra meaning to the + operator.
Code 1:
• Python3
# Python Program illustrate how
# to overload an binary + operator
class A:
def __init__(self, a):
self.a = a
print(ob1 + ob2)
print(ob3 + ob4)
Output :
GeeksFor
Code 2:
• Python3
# Python Program to perform addition
# of two complex numbers using binary
# + operator overloading.
class complex:
def __init__(self, a, b):
self.a = a
self.b = b
Ob1 = complex(1, 2)
Ob2 = complex(2, 3)
Ob3 = Ob1 + Ob2
print(Ob3)Output :
(3, 5)
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)
self.y = y
def __str__(self):
return "({0},{1})".format(self.x, self.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.
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)
Bitwise OR p1 | p2 p1.__or__(p2)
Dynamic attributes in Python are terminologies for attributes that are defined at runtime, after
creating the objects or instances. In Python we call all functions, methods also as an object. So you can
define a dynamic instance attribute for nearly anything in Python. Consider the below example for better
understanding about the topic.
Example 1:
class GFG:
None
def value():
return 10
# Driver Code
g = GFG()
# Dynamic attribute of a
# class object
g.d1 = value
# Dynamic attribute of a
# function
value.d1 = "Geeks"
print(value.d1)
print(g.d1() == value())
Output:
Geeks
True
Now, the above program seems to be confusing, but let’s try to understand it. Firstly let’s see the
objects, g and value(functions are also considered as objects in Python) are the two objects. Here the
dynamic attribute for both the objects is “d1”. This is defined at runtime and not at compile time like
static attributes.
Note: The class “GFG” and all other objects or instances of this class do not know the attribute “d1”. It
is only defined for the instance “g”.
Example 2:
class GFG:
employee = True
# Driver Code
e1 = GFG()
e2 = GFG()
e1.employee = False
e2.name = "Nikhil"
print(e1.employee)
print(e2.employee)
print(e2.name)
Output:
False
True
Nikhil
Traceback (most recent call last):
File "/home/fbcfcf668619b24bb8ace68e3c400bc6.py", line 19, in
print(e1.name)
AttributeError: 'GFG' object has no attribute 'name'
OOP in Python
Python is a great programming language that supports OOP. You will use it to define a class with
attributes and methods, which you will then call. Python offers a number of benefits compared to other
programming languages like Java, C++ or R. It's a dynamic language, with high-level data types. This
means that development happens much faster than with Java or C++. It does not require the programmer
to declare types of variables and arguments.
Python is a multi-paradigm programming language. It supports different programming approaches.
One of the popular approaches to solve a programming problem is by creating objects. This is known as
Object-Oriented Programming (OOP).
attributes
behavior
Class
A class is a blueprint for the object.
We can think of class as a sketch of a parrot with labels. It contains all the details about the name,
colors, size etc. Based on these descriptions, we can study about the parrot. Here, a parrot is an object.
The example for class of parrot can be :
class Parrot:
pass
Here, we use the class keyword to define an empty class Parrot. From class, we construct instances. An
instance is a specific object created from a particular class.
Object
An object (instance) is an instantiation of a class. When class is defined, only the description for the
object is defined. Therefore, no memory or storage is allocated.
The example for object of parrot class can be:
obj = Parrot()
Here, obj is an object of class Parrot.
Suppose we have details of parrots. Now, we are going to show how to build the class and objects of
parrots.
Example 1: Creating Class and Object in Python
class Parrot:
# class attribute
species = "bird"
# instance attribute
def __init__(self, name, age):
self.name = name
self.age = age
# instantiate the Parrot class
blu = Parrot("Blu", 10)
woo = Parrot("Woo", 15)
# access the class attributes
print("Blu is a {}".format(blu.__class__.species))
print("Woo is also a {}".format(woo.__class__.species))
def dance(self):
return "{} is now dancing".format(self.name)
# instantiate the object
blu = Parrot("Blu", 10)
# call our instance methods
print(blu.sing("'Happy'"))
print(blu.dance())
Output
Blu sings 'Happy'
Blu is now dancing
In the above program, we define two methods i.e sing() and dance(). These are called instance methods
because they are called on an instance object i.e blu.
Inheritance
Inheritance is a way of creating a new class for using details of an existing class without modifying it.
The newly formed class is a derived class (or child class). Similarly, the existing class is a base class (or
parent class).
Example 3: Use of Inheritance in Python
# parent class
class Bird:
def __init__(self):
print("Bird is ready")
def whoisThis(self):
print("Bird")
def swim(self):
print("Swim faster")
# child class
class Penguin(Bird):
def __init__(self):
# call super() function
super().__init__()
print("Penguin is ready")
def whoisThis(self):
print("Penguin")
def run(self):
print("Run faster")
peggy = Penguin()
peggy.whoisThis()
peggy.swim()
peggy.run()
Output
Bird is ready
Penguin is ready
Penguin
Swim faster
Run faster
In the above program, we created two classes i.e. Bird (parent class) and Penguin (child class). The child
class inherits the functions of parent class. We can see this from the swim() method.
Again, the child class modified the behavior of the parent class. We can see this from the whoisThis()
method. Furthermore, we extend the functions of the parent class, by creating a new run() method.
Additionally, we use the super() function inside the __init__() method. This allows us to run the
__init__() method of the parent class inside the child class.
Encapsulation
Using OOP in Python, we can restrict access to methods and variables. This prevents data from direct
modification which is called encapsulation. In Python, we denote private attributes using underscore as
the prefix i.e single _ or double __.
Example 4: Data Encapsulation in Python
class Computer:
def __init__(self):
self.__maxprice = 900
def sell(self):
print("Selling Price: {}".format(self.__maxprice))
Polymorphism
Polymorphism is an ability (in OOP) to use a common interface for multiple forms (data types).
Suppose, we need to color a shape, there are multiple shape options (rectangle, square, circle). However
we could use the same method to color any shape. This concept is called Polymorphism.
Example 5: Using Polymorphism in Python
class Parrot:
def fly(self):
print("Parrot can fly")
def swim(self):
print("Parrot can't swim")
class Penguin:
def fly(self):
print("Penguin can't fly")
def swim(self):
print("Penguin can swim")
# common interface
def flying_test(bird):
bird.fly()
#instantiate objects
blu = Parrot()
peggy = Penguin()
# passing the object
flying_test(blu)
flying_test(peggy)
Output
Parrot can fly
Penguin can't fly
In the above program, we defined two classes Parrot and Penguin. Each of them have a common fly()
method. However, their functions are different.
To use polymorphism, we created a common interface i.e flying_test() function that takes any object and
calls the object's fly() method. Thus, when we passed the blu and peggy objects in the flying_test()
function, it ran effectively.
Python Classes and Objects
A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means
of bundling data and functionality together. Creating a new class creates a new type of object, allowing
new instances of that type to be made
Class creates a user-defined data structure, which holds its own data members and member functions,
which can be accessed and used by creating an instance of that class. A class is like a blueprint for an
object.
class ClassName:
# Statement-1
.
.
.
# Statement-N
Example:
class Dog:
pass
In the above example, the class keyword indicates that you are creating a class followed by the name of
the class (Dog in this case).
Class Objects
An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of the class
with actual values. It’s not an idea anymore, it’s an actual dog, like a dog of breed pug who’s seven
years old. You can have many dogs to create many different instances, but without the class as a guide,
you would be lost, not knowing what information is required.
An object consists of :
State: It is represented by the attributes of an object. It also reflects the properties of an object.
Behavior: It is represented by the methods of an object. It also reflects the response of an object to other
objects.
Identity: It gives a unique name to an object and enables one object to interact with other objects.
python class
Example:
class Dog:
# A simple class
# attribute
attr1 = "mammal"
attr2 = "dog"
# A sample method
def fun(self):
print("I'm a", self.attr1)
print("I'm a", self.attr2)
# Driver code
# Object instantiation
Rodger = Dog()
class Account:
# Construct an Account object
def __init__(self, id, checkingBalance = 0, savingsBalance = 0, annualInterestRateSavings = 3.4):
self.id = id
self.checkingBalance = checkingBalance
self.savingsBalance = savingsBalance
self.annualInterestRateSavings = annualInterestRateSavings
def getId(self):
return self.id
def checkingAccountBalance(self):
return self.checkingBalance
def savingsAccountBalance(self):
return self.savingsBalance
def savingsAccountMonthlyInterest(self):
return self.savingsBalance * self.savingsAccountMonthlyInterest()
def savingsAccountAnnualInterestRate(self):
return self.annualInterestRateSavings
def savingsAccountMonthlyInterestRate(self):
return self.annualInterestRateSavings / 12
Inheritance is one of the most important aspects of Object Oriented Programming, as per object
oriented programming, we can take out the common part and put it in a separate class, and make all the
other classes inherit this class, to use its methods and variables, hence reducing re-writing the common
features in every class, again and again.
The class which inherits another class is generally known as the Child class, while the class which is
inherited by other classes is called as the Parent class.
If we have a class Parent and another class Child and we want the class Child to inherit the class Parent,
then
# Parent class
class Parent:
# class variable
a = 10;
b = 100;
# some class methods
def doThis();
def doThat();
def doWhat();
def doNotDoThat();
By specifying another class's name in parentheses, while declaring a class, we can specify inheritance. In
the example above, all the properties of Parent will be inherited to the Child class. With this, all the
methods and variables defined in the class Parent becomes part of Child class too.
1. Less code repeatition, as the code which is common can be placed in the parent class, hence
making it available to all the child classes.
2. Structured Code: By dividing the code into classes, we can structure our software better by
dividing functionality into classes.
3. Make the code more scalable.
While working in a child class, at some point you may have to use parent class's properties or functions.
In order to access parent class's elements you can use the dot . operator.
Parent.variableName
Mentioned above is how you can access the variable, or in case you need to call parent class's function
then,
Parent.functionName()
Where Parent is the name of our parent class, and variableName and functionName() are its variable and
function respectively.
class Parent:
var1 = 1
def func1(self):
# do something here
class Child(Parent):
var2 = 2
def func2(self):
# do something here too
# time to use var1 from 'Parent'
myVar = Parent.var1 + 10
return myVar
Polymorphism: The word polymorphism means having many forms. In programming, polymorphism
means the same function name (but different signatures) being used for different types.
Example of inbuilt polymorphic functions :
Output:
5
3
# Driver code
print(add(2, 3))
print(add(2, 3, 4))
Output:
5
9
Polymorphism with class methods:
The below code shows how Python can use two different class types, in the same way. We create a for
loop that iterates through a tuple of objects. Then call the methods without being concerned about
which class type each object is. We assume that these methods actually exist in each class.
class India():
def capital(self):
print("New Delhi is the capital of India.")
def language(self):
def type(self):
print("India is a developing country.")
class USA():
def capital(self):
print("Washington, D.C. is the capital of USA.")
def language(self):
print("English is the primary language of USA.")
def type(self):
print("USA is a developed country.")
obj_ind = India()
obj_usa = USA()
for country in (obj_ind, obj_usa):
country.capital()
country.language()
country.type()
Output:
New Delhi is the capital of India.
Hindi is the most widely spoken language of India.
India is a developing country.
Washington, D.C. is the capital of USA.
English is the primary language of USA.
USA is a developed country.
*************************END****************************************