0% found this document useful (0 votes)
5 views21 pages

Unit V Python

Unit V covers Object-Oriented Programming in Python, including concepts such as classes, objects, inheritance, encapsulation, polymorphism, and object persistence. It explains how to create classes and objects, the role of constructors and destructors, and various types of inheritance. Additionally, it discusses method overriding and polymorphism with examples to illustrate these concepts.

Uploaded by

dhirishathinad
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)
5 views21 pages

Unit V Python

Unit V covers Object-Oriented Programming in Python, including concepts such as classes, objects, inheritance, encapsulation, polymorphism, and object persistence. It explains how to create classes and objects, the role of constructors and destructors, and various types of inheritance. Additionally, it discusses method overriding and polymorphism with examples to illustrate these concepts.

Uploaded by

dhirishathinad
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/ 21

UNIT –V

UNIT V OBJECT ORIENTED PROGRAMMING IN PYTHON


Creating a Class, Class methods, Class Inheritance, Encapsulation,
Polymorphism, class method vs. static methods, Python object persistence

1. CLASS AND OBJECTS

 Class: The class is a user-defined data structure that binds the data members and
methods into a single unit. Class is a blueprint or code template for object
creation. Using a class, you can create as many objects as you want.
 Object: An object is an instance of a class. It is a collection of attributes
(variables) and methods. We use the object of a class to perform actions.
 Objects have two characteristics: They have states and behaviors (object has
attributes and methods attached to it) Attributes represent its state, and
methods represent its behavior. Using its methods, we can modify its state.
In short, every object has the following property.
 Identity: Every object must be uniquely identified.
 State: An object has an attribute that represents a state of an object, and it also
reflects the property of an object.
 Behavior: An object has methods that represent its behavior.
Example

A real-life example of class and objects.


Class: Person
 State: Name, Sex, Profession
 Behavior: Working, Study
Using the above class, we can create multiple objects that depict different states and
behavior.
Object 1: Jessa
 State:
 Name: Jessa
 Sex: Female

AVCCE/CA/TVN/SEM/I Page 1 of 21
UNIT –V

Profession: Software Engineer



Behavior:
 Working: She is working as a software developer at ABC Company

 Study: She studies 2 hours a day
Object 2: Jon
 State:
 Name: Jon
 Sex: Male
 Profession: Doctor
Behavior:
 Working: He is working as a doctor
 Study: He studies 5 hours a day
Create a Class in Python
 In Python, class is defined by using the class keyword. The syntax to create a
class is given below.
Syntax
class class_name:
<statement 1>
<statement 2>
.
.
<statement N>
Create Object of a Class
 An object is essential to work with the class attributes. The object is created using
the class name.
 In Python, Object creation is divided into two parts in Object Creation and Object
initialization
 Internally, the __new__ is the method that creates the object

 And, using the __init__() method we can implement constructor to initialize the
object.
Syntax
<object-name> = <class-name>(<arguments>)

Example Program:
class Person:
def __init__(self, name, sex, profession):
# data members (instance variables)
self.name = name
self.sex = sex

AVCCE/CA/TVN/SEM/I Page 2 of 21
UNIT –V

self.profession = profession
# Behavior (instance methods)
def show(self):
print('Name:', self.name, 'Sex:', self.sex, 'Profession:', self.profession)
# Behavior (instance methods)
def work(self):
print(self.name, 'working as a', self.profession)
# create object of a class
jessa = Person('Jessa', 'Female', 'Software Engineer')
# call methods
jessa.show()
jessa.work()

Class Attributes
In Class, attributes can be defined into two parts:
 Instance variables: The instance variables are attributes attached to an instance
of a class. We define instance variables in the constructor ( the __init__() method
of a class).
 Class Variables: A class variable is a variable that is declared inside of class, but
outside of any instance method or __init__() method.

AVCCE/CA/TVN/SEM/I Page 3 of 21
UNIT –V

Constructor in Python
A constructor is a special method used to create and initialize an object of a class
 The constructor is executed automatically at the time of object creation.
 The primary use of a constructor is to declare and initialize data
member/ instance variables of a class
Syntax
def __init__(self):
# body of the constructor
Where,
 def: The keyword is used to define function.
 __init__() Method: It is a reserved method. This method gets called as
soon as an object of a class is instantiated.
 self: The first argument self refers to the current object.

Example Program

class Student:
# class variables
school_name = 'ABC School'
# constructor
def __init__(self, name, age):
# instance variables
self.name = name
self.age = age

s1 = Student("Harry", 12)
# access instance variables
print('Student:', s1.name, s1.age)
# access class variable
print('School name:', Student.school_name)

# Modify instance variables


s1.name = 'Jessa'
s1.age = 14
print('Student:', s1.name, s1.age)
# Modify class variables
Student.school_name = 'XYZ School'
print('School name:', Student.school_name)

AVCCE/CA/TVN/SEM/I Page 4 of 21
UNIT –V

pass Statement in Class


 The pass statement is used to have an empty block in a code because the empty
code is not allowed in loops, function definition, class definition. Thus,
the pass statement will results in no operation (NOP).
 Example
class Demo:
pass
Modify Object Properties
 Every object has properties associated with them. We can set or modify the
object’s properties after object initialization by calling the property directly
using the dot operator.
Obj.PROPERTY = value
Delete object properties
 We can delete the object property by using the del keyword. After deleting it, if
we try to access it, we will get an error.
del object_name
 Example
class Fruit:
def __init__(self, name, color):
self.name = name
self.color = color
def show(self):
print("Fruit is", self.name, "and Color is", self.color)
# creating object of the class
obj = Fruit("Apple", "red")
obj.show()

AVCCE/CA/TVN/SEM/I Page 5 of 21
UNIT –V

# Modifying Object Properties


obj.name = "strawberry"
# calling the instance method using the object obj
obj.show()
# Output Fruit is strawberry and Color is red
del obj.name
obj.show()

Destructor
 The destructor is the reverse of the constructor. The constructor is used to
initialize objects, while the destructor is used to delete or destroy the object that
releases the resource occupied by the object.
 In Python, The special method __del__() is used to define a destructor.
 For example, when we execute del object_name destructor gets called
automatically and the object gets garbage collected.
 Syntax
def __del__(self):
# body of a destructor
 Example
class Student:
# constructor
def __init__(self, name):
print('Inside Constructor')
self.name = name
print('Object initialized')
def show(self):
print('Hello, my name is', self.name)
# destructor
def __del__(self):
print('Inside destructor')
print('Object destroyed')
# create object
s1 = Student('Raul')
s1.show()
# delete object
del s1

AVCCE/CA/TVN/SEM/I Page 6 of 21
UNIT –V

2. INHERITANCE IN PYTHON

 The process of inheriting the properties of the parent class into a child
class is called inheritance.
 The existing class is called a base class or parent class and the new class is called
a subclass or child class or derived class.
 The main purpose of inheritance is the reusability of code because we can use
the existing class to create a new class instead of creating it from scratch.
 For example, In the real world, Car is a sub-class of a Vehicle class. We can
create a Car by inheriting the properties of a Vehicle such as Wheels, Colors,
Fuel tank, engine, and add extra properties in Car as required
 Syntax

class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived class

Types of Inheritance
1. Single inheritance
2. Multiple Inheritance
3. Multilevel inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance
Single Inheritance
 In single inheritance, a child class inherits from a single-parent class. Here is one
child class and one parent class.

AVCCE/CA/TVN/SEM/I Page 7 of 21
UNIT –V

Example
# Base class
class Vehicle:
def Vehicle_info(self):
print('Inside Vehicle class')
# Child class
class Car(Vehicle):
def car_info(self):
print('Inside Car class')
# Create object of Car
car = Car()
# access Vehicle's info using car object
car.Vehicle_info()
car.car_info()

Multiple Inheritance
 In multiple inheritance, one child class can inherit from multiple parent classes.
So here is one child class and multiple parent classes.

Example
# Parent class 1
class Person:
def person_info(self, name, age):
print('Inside Person class')
print('Name:', name, 'Age:', age)
# Parent class 2
class Company:
def company_info(self, company_name, location):
print('Inside Company class')
print('Name:', company_name, 'location:', location)

AVCCE/CA/TVN/SEM/I Page 8 of 21
UNIT –V

# Child class
class Employee(Person, Company):
def Employee_info(self, salary, skill):
print('Inside Employee class')
print('Salary:', salary, 'Skill:', skill)
# Create object of Employee
emp = Employee()
# access data
emp.person_info('Jessa', 28)
emp.company_info('Google', 'Atlanta')
emp.Employee_info(12000, 'Machine Learning')

Multilevel inheritance
 In multilevel inheritance, a class inherits from a child class or derived class.
Suppose three classes A, B, C. A is the superclass, B is the child class of A, C is the
child class of B. In other words, we can say a chain of classes is called
multilevel inheritance.

Example
# Base class
class Vehicle:
def Vehicle_info(self):
print('Inside Vehicle class')
# Child class
class Car(Vehicle):
def car_info(self):
print('Inside Car class')
# Child class
class SportsCar(Car):

AVCCE/CA/TVN/SEM/I Page 9 of 21
UNIT –V

def sports_car_info(self):
print('Inside SportsCar class')
# Create object of SportsCar
s_car = SportsCar()
# access Vehicle's and Car info using SportsCar object
s_car.Vehicle_info()
s_car.car_info()
s_car.sports_car_info()
Output

Hierarchical Inheritance
 In Hierarchical inheritance, more than one child class is derived from a single
parent class. In other words, we can say one parent class and multiple child
classes

Example
class Vehicle:
def info(self):
print("This is Vehicle")
class Car(Vehicle):
def car_info(self, name):
print("Car name is:", name)
class Truck(Vehicle):
def truck_info(self, name):
print("Truck name is:", name)
obj1 = Car()
obj1.info()
obj1.car_info('BMW')
obj2 = Truck()
obj2.info()
obj2.truck_info('Ford')

AVCCE/CA/TVN/SEM/I Page 10 of 21
UNIT –V

Hybrid Inheritance
 When inheritance is consists of multiple types or a combination of different
inheritance is called hybrid inheritance

Example
class Vehicle:
def vehicle_info(self):
print("Inside Vehicle class")
class Car(Vehicle):
def car_info(self):
print("Inside Car class")

class Truck(Vehicle):
def truck_info(self):
print("Inside Truck class")
# Sports Car can inherits properties of Vehicle and Car
class SportsCar(Car, Vehicle):
def sports_car_info(self):
print("Inside SportsCar class")
# create object
s_car = SportsCar()
s_car.vehicle_info()
s_car.car_info()
s_car.sports_car_info()

Python super() function


 The super() function is used to give access to methods and properties of a
parent or sibling class.
 The super() function returns an object that represents the parent class.
 Example

AVCCE/CA/TVN/SEM/I Page 11 of 21
UNIT –V

class Company:
def company_name(self):
return 'Google'
class Employee(Company):
def info(self):
# Calling the superclass method using super()function
c_name = super().company_name()
print("Jessa works at", c_name)
# Creating object of child class
emp = Employee()
emp.info()
Output

METHOD OVERRIDING
 In inheritance, all members available in the parent class are by default available in
the child class. If the child class does not satisfy with parent class implementation,
then the child class is allowed to redefine that method by extending additional
functions in the child class. This concept is called method overriding.
 When a child class method has the same name, same parameters, and same return
type as a method in its superclass, then the method in the child is said
to override the method in the parent class.
 Example

Example
class Vehicle:
def max_speed(self):
print("max speed is 100 Km/Hour")
class Car(Vehicle):
# overridden the implementation of Vehicle class
def max_speed(self):

AVCCE/CA/TVN/SEM/I Page 12 of 21
UNIT –V

super().max_speed()
print("max speed is 200 Km/Hour")

# Creating object of Car class


car = Car()
car.max_speed()

3. POLYMORPHISM
 The word polymorphism means having many forms.
 Polymorphism means the same function name (but different signatures) being
used for different types. The key difference is the data types and number of
arguments used in function
Polymorphism in Built-in function len()
 The built-in function len() calculates the length of an object depending upon its
type. If an object is a string, it returns the count of characters, and if an object is
a list, it returns the count of items in a list.
 Example
students = ['Raja', 'Raul', 'Robin']
school = 'ABC School'
# calculate count
print(len(students))
print(len(school))
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.
 [[ Example
class India():
def capital(self):
print("New Delhi is the capital 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 type(self):
print("USA is a developed country.")

AVCCE/CA/TVN/SEM/I Page 13 of 21
UNIT –V

obj_ind = India()
obj_usa = USA()
for country in (obj_ind, obj_usa):
country.capital()
country.type()
Output
New Delhi is the capital of India.
India is a developing country.
Washington, D.C. is the capital of USA.
USA is a developed country.

Method Overloading
 The process of calling the same method with different parameters is known as
method overloading. Python does not support method overloading.
 Python considers only the latest defined method even if you overload the
method. Python will raise a TypeError if you overload the method.
 To overcome the above problem, we can use different ways to achieve the
method overloading. In Python, to overload the class method, we need to write
the method’s logic so that different code executes inside the function depending
on the parameter passes.
 Example

class Shape:
# function with two default parameters
def area(self, a, b=0):
if b > 0:
print('Area of Rectangle is:', a * b)
else:
print('Area of Square is:', a ** 2)
square = Shape()
square.area(5,3)
square.area(5)
Output

Operator Overloading in Python


 Operator overloading means changing the default behavior of
an operator depending on the operands (values) that we use. In other words, we
can use the same operator for multiple purposes.

AVCCE/CA/TVN/SEM/I Page 14 of 21
UNIT –V

Example
class Book:
def __init__(self, pages):
self.pages = pages
# Overloading + operator with magic method
def __add__(self, other):
return self.pages + other.pages
b1 = Book(400)
b2 = Book(300)
print("Total number of pages: ", b1 + b2)

Magic Methods
 Magic methods are special methods in python that have double underscores on
both sides of the method name. Magic methods are predominantly used for
operator overloading.
 Operator overloading means provided additional functionality to the operators,
the python implicitly invokes the magic methods to provide additional
functionality to it.

4. CLASS METHODS
In Object-oriented programming, Inside a Class, we can define the following three
types of methods.
 Instance method: Used to access or modify the object state. If we use instance
variables inside a method, such methods are called instance methods.
 Class method: Used to access or modify the class state. In method
implementation, if we use only class variables, then such type of methods we
should declare as a class method.
 Static method: It is a general utility method that performs a task in isolation.
Inside this method, we don’t use instance or class variable because this static
method doesn’t have access to the class attributes.

AVCCE/CA/TVN/SEM/I Page 15 of 21
UNIT –V

Example
class Student:
# class variable
school_name = 'ABC School'
# constructor
def __init__(self, name, age):
# instance variables
self.name = name
self.age = age
# instance method
def show(self):
# access instance variables and class variables
print('Student:', self.name, self.age, Student.school_name)
# class method
@classmethod
def modify_school_name(cls, new_name):
# modify class variable
cls.school_name = new_name
s1 = Student("Harry", 12)
# call instance methods
s1.show()
# call class method
Student.modify_school_name('XYZ School')
# call instance methods
s1.show()

STATIC METHOD
 A static method is a method which is bound to the class and not the object of
the class. It can’t access or modify class state.
 A static method does not receive an implicit first argument.
 Syntax:
class C(object):
@staticmethod
def fun(arg1, arg2, ...):
 When function decorated with @staticmethod is called, we don’t pass an
instance of the class to it as it is normally done with methods.
 It means that the function is put inside the class but it cannot access the
instance of that class.

AVCCE/CA/TVN/SEM/I Page 16 of 21
UNIT –V

 Example
class Employee:
@staticmethod
def sample(x):
print('Inside static method', x)
# call static method
Employee.sample(10)
# can be called using object
emp = Employee()
emp.sample(1)

Comparison between Instance Methods, Class Methods and Static Methods

AVCCE/CA/TVN/SEM/I Page 17 of 21
UNIT –V

5. ENCAPSULATION
 Encapsulation in Python describes the concept of bundling data
and methods within a single unit. So, for example, when you create a class, it
means you are implementing encapsulation.
 A class is an example of encapsulation as it binds all the data members (instance
variables) and methods into a single unit.

Example
class Students:
def __init__(self, name, rank, points):
self.name = name
self.rank = rank
self.points = points
# custom function
def demofunc(self):
print("I am "+self.name)
print("I got Rank ",+self.rank)
# create an objects
st1 = Students("Steve", 1, 100)
# call the functions using the objects created above
st1.demofunc()
Output
I am Steve
I got Rank 1
 Using encapsulation, we can hide an object’s internal representation from the
outside. This is called information hiding.
Access Modifiers in Python
 Let us see the access modifiers in Python to understand the concept of
Encapsulation and data hiding .
The public Access Modifier
o The public member is accessible from inside or outside the class.
o Example
age

AVCCE/CA/TVN/SEM/I Page 18 of 21
UNIT –V

The private Access Modifier


o The private member is accessible only inside class. Define a private
member by prefixing the member name with two underscores, for
example
__age
The protected Access Modifier
 The protected member is accessible. from inside the class and its sub-class.
Define a protected member by prefixing the member name with an underscore,
for example
_age

Example
# base class
class Company:
def __init__(self):
# Protected member
self._project = "NLP"
# child class
class Employee(Company):
def __init__(self, name):
self.name = name
Company.__init__(self)
def show(self):
print("Employee name :", self.name)
# Accessing protected member in child class
print("Working on project :", self._project)
c = Employee("Raul")
c.show()
# Direct access protected data member
print('Project:', c._project)

AVCCE/CA/TVN/SEM/I Page 19 of 21
UNIT –V

Getters and Setters in Python


 The primary purpose of using getters and setters in object-oriented programs is
to ensure data encapsulation.
 Use the getter method to access data members and the setter methods to
modify the data members.

 Example
class Student:
def __init__(self, name, age):
# private member
self.name = name
self.__age = age
# getter method
def get_age(self):
return self.__age
# setter method
def set_age(self, age):
self.__age = age
stud = Student('Raja', 14)
# retrieving age using getter
print('Name:', stud.name, stud.get_age())
# changing age using setter
stud.set_age(16)
# retrieving age using getter
print('Name:', stud.name, stud.get_age())

Advantages of Encapsulation
 Security
 Data Hiding
 Simplicity

6. PYTHON OBJECT PERSISTENCE
 Using the Persistent Storage module, Python objects can store themselves in
relational database systems.
 The Persistent Storage module abstracts and hides the underlying database
interface, such as the Sybase Module and the newer Python Database API.
 Persistent objects implement data management methods such as save and delete.
 The shelve module in Python’s standard library provides simple yet effective
object persistence mechanism.

AVCCE/CA/TVN/SEM/I Page 20 of 21
UNIT –V

Shelve Module Description


Shelf This is the base class for shelf implementations.
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
DbfilenameShelf This is also a subclass of Shelf but accepts a filename as
parameter to its constructor

 The Shelf object has following methods available


Method Description
close() synchronies and close persistent dict object
get() returns value associated with key
items() list of tuples – each tuple is key value pair
keys() list of shelf keys
pop() Remove specified key and return the corresponding value.
update() Update shelf from another dict/iterable
values() list of shelf values
Example
import shelve
s=shelve.open("test")
s['name']="Ajay"
s['age']=23
s['marks']=75
print (s['age'])
s['age']=25
print (s.get('age'))
s.close()

************

AVCCE/CA/TVN/SEM/I Page 21 of 21

You might also like