Python PDF
Python PDF
class ClassName:
# Statement-1
.
.
.
# Statement-N
# a class
class Dog:
pass
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.
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
Pet = Dog()
Output:
mammal
I'm a mammal
I'm a dog
__init__ method
The __init__ method is similar to constructors in C++ and Java. Constructors are used to initializing the object‟s
state. Like methods, a constructor also contains a collection of statements(i.e. instructions) that are executed at
the time of Object creation. It runs as soon as an object of a class is instantiated. The method is useful to do any
initialization you want to do with your object.
# A Sample class with init method
class Person:
p = Person('Nikhil')
p.say_hi()
Output:
Hello, my name is Nikhil
# Class Variable
animal = 'dog'
# Instance Variable
self.breed = breed
self.color = color
print('Pet details:')
print('Pet is a', Pet.animal)
print('Breed: ', Pet.breed)
print('Color: ', Pet.color)
print('\nBuzo details:')
print('Buzo is a', Buzo.animal)
print('Breed: ', Buzo.breed)
print('Color: ', Buzo.color)
Buzo details:
Buzo is a dog
Breed: Bulldog
Color: black
# Class Variable
animal = 'dog'
# Instance Variable
self.breed = breed
# Driver Code
Pet = Dog("pug")
Pet.setColor("brown")
print(Pet.getColor())
Output:
brown
OOPs Concepts
Main Concepts of Object-Oriented Programming (OOPs)
Class
Objects
Polymorphism
Encapsulation
Inheritance
Class
A class is a collection of objects. A class contains the blueprints or the prototype from which the objects are being
created. It is a logical entity that contains some attributes and methods.
To understand the need for creating a class let‟s consider an example, let‟s say you wanted to track the number of
dogs that may have different attributes like breed, age. If a list is used, the first element could be the dog‟s breed
while the second element could represent its age. Let‟s suppose there are 100 different dogs, then how would you
know which element is supposed to be which? What if you wanted to add other properties to these dogs? This
lacks organization and it‟s the exact need for classes.
Some points on Python class:
Classes are created by keyword class.
Attributes are the variables that belong to a class.
Attributes are always public and can be accessed using the dot (.) operator. Eg.: Myclass.Myattribute
Class Definition Syntax:
class ClassName:
# Statement-1
.
.
.
# Statement-N
# Python3 program to
# demonstrate defining
# a class
class Dog:
pass
Objects
The object is an entity that has a state and behavior associated with it. It may be any real-world object like a
mouse, keyboard, chair, table, pen, etc. Integers, strings, floating-point numbers, even arrays, and dictionaries,
are all objects. More specifically, any single integer or any single string is an object. The number 12 is an object,
the string “Hello, world” is an object, a list is an object that can hold other objects, and so on. You‟ve been using
objects all along and may not even realize it.
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.
To understand the state, behavior, and identity let us take the example of the class dog (explained above).
The identity can be considered as the name of the dog.
State or Attributes can be considered as the breed, age, or color of the dog.
The behavior can be considered as to whether the dog is eating or sleeping.
This will create an object named obj of the class Dog defined above. Before diving deep into objects and class let
us understand some basic keywords that will we used while working with objects and classes.
The self
1. Class methods must have an extra first parameter in the method definition. We do not give a value for this
parameter when we call the method, Python provides it
2. If we have a method that takes no arguments, then we still have to have one argument.
3. This is similar to this pointer in C++ and this reference in Java.
When we call a method of this object as myobject.method(arg1, arg2), this is automatically converted by Python
into MyClass.method(myobject, arg1, arg2) – this is all the special self is about.
Note: For more information, refer to self in Python class
Example 1: Creating a class and object with class and instance attributes
class Dog:
# class attribute
attr1 = "mammal"
# Instance attribute
def __init__(self, name):
self.name = name
# Driver code
# Object instantiation
Pet = Dog("Pet")
Tommy = Dog("Tommy")
Output
Pet is a mammal
Tommy is also a mammal
My name is Pet
My name is Tommy
Creating Class and objects with methods
class Dog:
# class attribute
attr1 = "mammal"
# Instance attribute
def __init__(self, name):
self.name = name
def speak(self):
print("My name is {}".format(self.name))
# Driver code
# Object instantiation
Pet = Dog("Pet")
Tommy = Dog("Tommy")
Inheritance
Inheritance is the capability of one class to derive or inherit the properties from another class. The class that
derives properties is called the derived class or child class and the class from which the properties are being
derived is called the base class or parent class. The benefits of inheritance are:
It represents real-world relationships well.
It provides the 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 is transitive in nature, which means that if class B inherits from another class A, then all the subclasses of
B would automatically inherit from class A.
# parent class
class Person(object):
def display(self):
print(self.name)
print(self.idnumber)
def details(self):
print("My name is {}".format(self.name))
print("IdNumber: {}".format(self.idnumber))
# child class
class Employee(Person):
def __init__(self, name, idnumber, salary, post):
self.salary = salary
self.post = post
def details(self):
print("My name is {}".format(self.name))
print("IdNumber: {}".format(self.idnumber))
print("Post: {}".format(self.post))
Polymorphism
Polymorphism simply means having many forms. For example, we need to determine if the given species of birds
fly or not, using polymorphism we can do this using a single function.
class Bird:
def intro(self):
print("There are many types of birds.")
def flight(self):
print("Most of the birds can fly but some cannot.")
class sparrow(Bird):
def flight(self):
print("Sparrows can fly.")
class ostrich(Bird):
def flight(self):
print("Ostriches cannot fly.")
obj_bird = Bird()
obj_spr = sparrow()
obj_ost = ostrich()
obj_bird.intro()
obj_bird.flight()
obj_spr.intro()
obj_spr.flight()
obj_ost.intro()
obj_ost.flight()
Output
There are many types of birds.
Most of the birds can fly but some cannot.
There are many types of birds.
Sparrows can fly.
There are many types of birds.
Ostriches cannot fly.
Encapsulation
Encapsulation is one of the fundamental concepts in object-oriented programming (OOP). It describes the idea of
wrapping data and the methods that work on data within one unit. This puts restrictions on accessing variables
and methods directly and can prevent the accidental modification of data. To prevent accidental change, an
object‟s variable can only be changed by an object‟s method. Those types of variables are known as private
variables.
A class is an example of encapsulation as it encapsulates all the data that is member functions, variables, etc.
# Python program to
# demonstrate private members
# Calling constructor of
# Base class
Base.__init__(self)
print("Calling private member of base class: ")
print(self.__c)
# Driver code
obj1 = Base()
print(obj1.a)
Every object, either for Data Modelling in Python or any other activity involving Python‟s environment, has an
identity which can never change once it is created. Think of identity as an object‟s address in the memory.
id() is the function that gives us the identity of the object or we can say it returns the virtual memory address of the
object. The memory address will be an integer value.
>>> a='hevodata'
>>> id(a)
1397871458544
>>> b=101
>>> id(b)
1623965024
>>> c='hevodata'
>>> id(c)
1397871458544
>>> a is b
False
>>> a is c
True
Type of an Object
During Data Modelling in Python, the type of an object means the name of the class to which the object belongs.
Function type() tells the type of the object. By knowing the type of an object, it is easy for user‟s to specify two
things.
The operation allowed on that object
The set of values the object can hold.
Python Code:
a='hevodata'
x=type(a)
print("Type of variable 'a' is: ", x)
Type of variable 'a' is: <class 'str'>
b=101
y= type(b)
print("Type of variable 'b' is: ", y)
Type of variable 'b' is: <class 'int'>
An object‟s value during Data Modelling in Python is the data that is stored for that object. The value object can
hold is decided on the basis of the type of object.
Python Code:
var='article'
print("Value of variable 'var' is: ", var)
Value of variable 'var' is: article
Object values are changeable and it depends on their type. Python supports the following 2 types of objects based on
their values:
Mutable Objects
Immutable Objects
There is some type for which the value of an object cannot change those are called immutable objects and whose
value can be changed are called mutable objects.
1) Mutable Objects
The mutability of objects is decided on the basis of their type. Lists, Dictionaries are mutable objects. Those objects
whose values can be changed are called Mutable objects.
The following Python code is useful for creating a list for Data Modelling in Python:
#Let's create a list
>>> a = [11, 22, 33]
>>> print("List values: ",a)
>>> print("Identity of a: ",id(a))
List values: [11, 22, 33]
Identity of a: 1397871407048
During Data Modelling in Python, Immutable Objects are the objects that stored data but their values cannot be
modified. Numbers, Strings, Tuples, and Sets are immutable.
The following Python code is useful for creating a variable with string value during Data Modelling in Python:
#Let's create a varible with string value
s = "Hevo"
print("Variable value: ",s)
print("Identity of s: ",id(s))
Variable value: Hevo
Identity of s: 1397871732528
def __len__(self):
return len(self._data)
1 Shelf
This is the base class for shelf implementations. It is initialized with dict-like object.
2 BsdDbShelf
This is a subclass of Shelf class. The dict object passed to its constructor must support first(), next(),
previous(), last() and set_location() methods.
3 DbfilenameShelf
This is also a subclass of Shelf but accepts a filename as parameter to its constructor rather than dict
object.
open(filename, flag = 'c', protocol=None, writeback = False)
The filename parameter is assigned to the database created.
Default value for flag parameter is „c‟ for read/write access. Other flags are „w‟ (write only) „r‟ (read only) and „n‟
(new with read/write)
Protocol parameter denotes pickle protocol writeback parameter by default is false. If set to true, the accessed
entries are cached. Every access calls sync() and close() operations hence process may be slow.
Following code creates a database and stores dictionary entries in it.
import shelve
s = shelve.open("test")
s['name'] = "Ajay"
s['age'] = 23
s['marks'] = 75
s.close()
This will create test.dir file in current directory and store key-value data in hashed form. The Shelf object has
following methods available −
Sr.No. Method & Description
1 close()
synchronise and close persistent dict object.
2 sync()
Write back all entries in the cache if shelf was opened with writeback set to True.
3 get()
returns value associated with key
4 items()
list of tuples – each tuple is key value pair
5 keys()
list of shelf keys
6 pop()
remove specified key and return the corresponding value.
7 update()
Update shelf from another dict/iterable
8 values()
list of shelf values
To access value of a particular key in shelf.
>>> s=shelve.open('test')
>>> s['age']
23
>>> s['age']=25
>>> s.get('age')
25
The items(), keys() and values() methods return view objects.
>>> list(s.items())
[('name', 'Ajay'), ('age', 25), ('marks', 75)]
>>> list(s.keys())
['name', 'age', 'marks']
>>> list(s.values())
['Ajay', 25, 75]
To remove a key-value pair from shelf
>>> s.pop('marks')
75
>>> list(s.items())
[('name', 'Ajay'), ('age', 25)]
Notice that key-value pair of marks-75 has been removed.
To merge items of another dictionary with shelf use update() method
>>> d={'salary':10000, 'designation':'manager'}
>>> s.update(d)
>>> list(s.items())
[('name', 'Ajay'), ('age', 25), ('salary', 10000), ('designation', 'manager')]
Inheritance
Inheritance is the capability of one class to derive or inherit the properties from another class. The benefits of
inheritance are:
# Constructor
def __init__(self, name):
self.name = name
# To get name
def getName(self):
return self.name
# Driver code
emp = Person("Good1") # An Object of Person
print(emp.getName(), emp.isEmployee())
Output:
Good1 False
Good2 True
# parent class
class Person( object ):
# child class
class Employee( Person ):
def __init__(self, name, idnumber, salary, post):
self.salary = salary
self.post = post
class Base2(object):
def __init__(self):
self.str2 = "Good2"
print("Base2")
def printStrs(self):
print(self.str1, self.str2)
ob = Derived()
ob.printStrs()
Output:
Base1
Base2
Derived
Good1 Good2
# To get name
def getName(self):
return self.name
# Constructor
def __init__(self, name, age):
Base.__init__(self, name)
self.age = age
# To get name
def getAge(self):
return self.age
# Constructor
def __init__(self, name, age, address):
Child.__init__(self, name, age)
self.address = address
# To get address
def getAddress(self):
return self.address
# Driver code
g = GrandChild("Good1", 23, "Noida")
print(g.getName(), g.getAge(), g.getAddress())
Output:
Good1 23 Noida
5. Hierarchical inheritance More than one derived classes are created from a single base.
5. Hybrid inheritance: This form combines more than one form of inheritance. Basically, it is a blend of
more than one type of inheritance.
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 :
# Python program to demonstrate in-built poly-
# morphic functions
# Driver code
print(add(2, 3))
print(add(2, 3, 4))
Output:
5
9
def language(self):
print("Hindi is the most widely spoken
language of India.")
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.
class Bird:
def intro(self):
print("There are many types of birds.")
def flight(self):
print("Most of the birds can fly but some cannot.")
class sparrow(Bird):
def flight(self):
print("Sparrows can fly.")
class ostrich(Bird):
def flight(self):
print("Ostriches cannot fly.")
obj_bird = Bird()
obj_spr = sparrow()
obj_ost = ostrich()
obj_bird.intro()
obj_bird.flight()
obj_spr.intro()
obj_spr.flight()
obj_ost.intro()
obj_ost.flight()
Output:
There are many types of birds.
Most of the birds can fly but some cannot.
There are many types of birds.
Sparrows can fly.
There are many types of birds.
Ostriches cannot fly.
obj_ind = India()
obj_usa = USA()
func(obj_ind)
func(obj_usa)
Operator Overloading
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)
print("Goods"*4)
Output
3
GoodsFor
12
GoodsGoodsGoodsGoods
Output:
3
GoodsFor
12
GoodsGoodsGoodsGoods
class A:
def __init__(self, a):
self.a = a
print(ob1 + ob2)
print(ob3 + ob4)
Output
3
GoodsFor
Output :
3
GoodsFor
class A:
def __init__(self, a):
self.a = a
def __gt__(self, other):
if(self.a>other.a):
return True
else:
return False
ob1 = A(2)
ob2 = A(3)
if(ob1>ob2):
print("ob1 is greater than ob2")
else:
print("ob2 is greater than ob1")
Output :
class A:
def __init__(self, a):
self.a = a
ob1 = A(2)
ob2 = A(3)
print(ob1~ob2)
Abstract classes
An abstract class can be considered as a blueprint for other classes. It allows you to create a set of
methods that must be created within any child classes built from the abstract class. A class which
contains one or more abstract methods is called an abstract class. An abstract method is a method that
has a declaration but does not have an implementation. While we are designing large functional units we
use an abstract class. When we want to provide a common interface for different implementations of a
component, we use an abstract class.
Why use Abstract Base Classes :
By defining an abstract base class, you can define a common Application Program Interface(API) for a
set of subclasses. This capability is especially useful in situations where a third-party is going to provide
implementations, such as with plugins, but can also help you when working in a large team or with a
large code-base where keeping all classes in your mind is difficult or not possible.
How Abstract Base classes work :
By default, Python does not provide abstract classes. Python comes with a module that provides the base
for defining Abstract Base classes(ABC) and that module name is ABC. ABC works by decorating
methods of the base class as abstract and then registering concrete classes as implementations of the
abstract base.
# Python program showing
# abstract base class work
class Polygon(ABC):
@abstractmethod
def noofsides(self):
pass
class Triangle(Polygon):
class Pentagon(Polygon):
class Hexagon(Polygon):
class Quadrilateral(Polygon):
# Driver code
R = Triangle()
R.noofsides()
K = Quadrilateral()
K.noofsides()
R = Pentagon()
R.noofsides()
K = Hexagon()
K.noofsides()
Output:
I have 3 sides
I have 4 sides
I have 5 sides
I have 6 sides
def move(self):
pass
class Human(Animal):
def move(self):
print("I can walk and run")
class Snake(Animal):
def move(self):
print("I can crawl")
class Dog(Animal):
def move(self):
print("I can bark")
class Lion(Animal):
def move(self):
print("I can roar")
# Driver code
R = Human()
R.move()
K = Snake()
K.move()
R = Dog()
R.move()
K = Lion()
K.move()
Output:
import abc
class parent:
def Goods(self):
pass
class child(parent):
def Goods(self):
print("child class")
# Driver code
print( issubclass(child, parent))
print( isinstance(child(), parent))
Output:
True
True
Exception Handling
Difference between Syntax Error and Exceptions
Syntax Error: As the name suggests this error is caused by the wrong syntax in the code. It leads to the
termination of the program.
# initialize the amount variable
amount = 10000
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
except:
print ("An error occurred")
Output
Second element = 2
An error occurred
def fun(a):
if a < 4:
# throws ZeroDivisionError for a = 3
b = a/(a-3)
try:
fun(3)
fun(5)
except:
# optional block
# Handling of exception (if required)
else:
# execute if no exception
finally:
# Some code .....(always executed)
# Python program to demonstrate finally
finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
Output:
Can't divide by zero
This is always executed
Try
The try block lets you test a block of code for errors.
The except block lets you handle the error.
The else block lets you execute code when there is no error.
The finally block lets you execute code, regardless of the result of the try- and except blocks.
Exception Handling
When an error occurs, or exception as we call it, Python will normally stop and generate an error message.
try:
print(x)
except:
print("An exception occurred")
Else
You can use the else keyword to define a block of code to be executed if no errors were raised:
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
C:\Users\My Name>python demo_try_except5.py
Something went wrong when writing to the file