0% found this document useful (0 votes)
3 views

python unit 3 (1)

Uploaded by

bhoibazigar007
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

python unit 3 (1)

Uploaded by

bhoibazigar007
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Ankur

(Python [601] – Unit 3)


COLLEGE ==> MATRUSHRI L.J.
GANDHI BCA COLLEGE, MODASA
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON

List in python
 A list in Python is used to store the sequence of various types of data.
 Python lists are mutable type its mean we can modify its element after it created.
 A list can be defined as a collection of values or items of different types.
 The items in the list are separated with the comma (,) and enclosed with square brackets [ ].
 A list can be define as below
L1 = ["Daksh", 107, "Naksh"]
L2 = [1, 2, 3, 4, 5, 6,7]

Add/Change List Elements


 Lists are mutable, meaning their elements can be changed unlike string or tuple.
 We can use the assignment operator = to change an item or a range of items.
Example :
# Correcting mistake values in a list
odd = [2, 4, 6, 8]

# change the 1st item


odd[0] = 1
print(odd) #Output : [1, 4, 6, 8]

# change 2nd to 4th items


odd[1:4] = [3, 5, 7]
print(odd) #Output : [1, 3, 5, 7]

 We can add one item to a list using the append() method or add several items using the
extend() method.
Example :
# Appending and Extending lists in Python
odd = [1, 3, 5]
odd.append(7)
print(odd) #Output : [1, 3, 5, 7]

odd.extend([9, 11, 13])


print(odd) #Output : [1, 3, 5, 7, 9, 11, 13]

ANKUR 1
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON

 We can also use + operator to combine two lists which is also called concatenation.
 The * operator repeats a list for the given number of times.
Example :
# Concatenating and repeating lists
odd = [1, 3, 5]
print(odd + [9, 7, 5]) #Output : [1, 3, 5, 9, 7, 5]
print(["re"] * 3) #Output : ['re', 're', 're']

 Further, we can insert one item at a desired location by using the method insert() or insert
multiple items by squeezing it into an empty slice of a list.
Example :
# Demonstration of list insert() method
odd = [1, 9]
odd.insert(1,3)
print(odd) #Output : [1, 3, 9]
odd[2:2] = [5, 7]
print(odd) #Output : [1, 3, 5, 7, 9]

Delete List Elements


 We can delete one or more items from a list using the Python del statement. It can even
delete the list entirely.
Example :
# Deleting list items
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']

# delete one item


del my_list[2]
print(my_list) #Output : ['p', 'r', 'b', 'l', 'e', 'm']

# delete multiple items


del my_list[1:5]
print(my_list) #Output : ['p', 'm']

ANKUR 2
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON

# delete the entire list


del my_list
print(my_list) #Output : NameError: name 'my_list' is not defined

 We can use remove() to remove the given item or pop() to remove an item at the given index.
 The pop() method removes and returns the last item if the index is not provided.
Example :
my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')
print(my_list) # Output: ['r', 'o', 'b', 'l', 'e', 'm']
print(my_list.pop(1)) # Output: 'o'
print(my_list) # Output: ['r', 'b', 'l', 'e', 'm']
print(my_list.pop()) # Output: 'm'
print(my_list) # Output: ['r', 'b', 'l', 'e']

my_list.clear()
print(my_list) # Output: []

Access List Elements


 We can use the index operator [ ] to access an item in a list.
 In Python, indices start at 0. So, a list having 5 elements will have an index from 0 to 4.
 Trying to access indexes other than these will raise an IndexError.
 The index must be an integer. We can't use float or other types, this will result in TypeError.
 Nested lists are accessed using nested indexing.
Example :
my_list = ['p', 'r', 'o', 'b', 'e']

# first item
print(my_list[0]) # Output: p

# third item
print(my_list[2]) # Output: o

ANKUR 3
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON

# fifth item
print(my_list[4]) # Output: e

# Nested List
n_list = ["Happy", [2, 0, 1, 5]]

# Nested indexing
print(n_list[0][1]) # Output: a
print(n_list[1][3]) # Output: 5

# Error! Only integer can be used for indexing


print(my_list[4.0]) # Output: TypeError: list indices must be integers, not float

 Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2
to the second last item and so on.
Example :
# Negative indexing in lists
my_list = ['p','r','o','b','e']
# last item
print(my_list[-1]) # Output: e
# fifth last item
print(my_list[-5]) # Output: p

Example :
# List slicing in Python
my_list = ['p','r','o','g','r','a','m','i','z']
# elements from index 2 to index 4
print(my_list[2:5]) # Output: ['o', 'g', 'r']
# elements from index 5 to end
print(my_list[5:]) # Output: ['a', 'm', 'i', 'z']
# elements beginning to end
print(my_list[:]) # Output: ['p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z']

ANKUR 4
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON

List Operators
 Like the string, the list is also a sequence.
 Hence, the operators used with strings are also available for use with the list (and tuple also).

Operator Example

The + operator returns a list containing all the elements of >>> L1=[1,2,3]
the first and the second list. >>> L2=[4,5,6]
>>> L1+L2
[1, 2, 3, 4, 5, 6]
The * operator concatenates multiple copies of the same list. >>> L1=[1,2,3]
>>> L1*3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
The slice operator [] returns the item at the given index. >>> L1=[1, 2, 3]
A negative index counts the position from the right side. >>> L1[0]
1
>>> L1[-3]
1
>>> L1[1]
2
>>> L1[-2]
2
>>> L1[2]
3
>>> L1[-1]
3
The range slice operator [FromIndex : Untill Index - 1] >>> L1=[1, 2, 3, 4, 5, 6]
fetches items in the range specified by the two index >>> L1[1:]
operands separated by : symbol. [2, 3, 4, 5, 6]
>>> L1[:3]
[1, 2, 3]
>>> L1[3:]
[4, 5, 6]
The in operator returns true if an item exists in the given list. >>> L1=[1, 2, 3, 4, 5, 6]
>>> 4 in L1
True
>>> 10 in L1
False

ANKUR 5
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON

The not in operator returns true if an item does not exist in >>> L1=[1, 2, 3, 4, 5, 6]
the given list. >>> 5 not in L1
False
>>> 10 not in L1
True

Python List Methods


 Python has many useful list methods that makes it really easy to work with lists.
Methods Descriptions
append() adds an element to the end of the list
extend() adds all elements of a list to another list
insert() inserts an item at the defined index
remove() removes an item from the list
pop() returns and removes an element at the given index
clear() removes all items from the list
index() returns the index of the first matched item
count() returns the count of the number of items passed as an argument
sort() sort items in a list in ascending order
reverse() reverse the order of items in the list
copy() returns a shallow copy of the list

Example : Remove the duplicate element of the list.


list1 = [1,2,2,3,55,98,65,65,13,29]
# Declare an empty list that will store unique values
list2 = []
for i in list1:
if i not in list2:
list2.append(i)
print(list2)

Output :
[1, 2, 3, 55, 98, 65, 13, 29]

ANKUR 6
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON

Example : Find the sum of the element in the list.


list1 = [3,4,5,9,10,12,24]
sum = 0
for i in list1:
sum = sum+i
print("The sum is:",sum)

Output :
The sum is: 67

Iterate List
 A list items can be iterate using the for loop.
Example :
names=["Daksh", "Naksh", "Krunal"]
for name in names:
print(name)

Output :
Daksh
Naksh
Krunal

Iterating Through a List


 Using a for loop we can iterate through each item in a list.
Example :
for fruit in ['apple','banana','mango']:
print("I like",fruit)

Output :
I like apple
I like banana
I like mango

ANKUR 7
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON

tuple in python
 Python Tuple is used to store the sequence of immutable Python objects.
 The Tuple is similar to lists since the value of the items stored in the list can be changed,
whereas the value of the items stored in the tuple cannot be changed.

Creating a tuple
 A tuple can be written as the collection of comma-separated (,) values enclosed with the
small () brackets.
 The parentheses are optional but it is good practice to use.
 A tuple can be defined as follows.
T1 = ("Daksh", 107, "Naksh")
T2 = ("Apple", "Banana", "Orange")
T3 = 10,20,30,40,50

 Unlike lists, tuples are immutable.


 This means that elements of a tuple cannot be changed once they have been assigned. But, if
the element is itself a mutable data type like a list, its nested items can be changed.
 We can also assign a tuple to different values (reassignment).
Example :
# Changing tuple values
my_tuple = (4, 2, 3, [6, 5])

# TypeError: 'tuple' object does not support item assignment


my_tuple[1] = 9

# However, item of mutable element can be changed


my_tuple[3][0] = 9
print(my_tuple) # Output: (4, 2, 3, [9, 5])

# Tuples can be reassigned


my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple) # Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

 We can use + operator to combine two tuples which is called concatenation.


 We can also repeat the elements in a tuple for a given number of times using the * operator.
 Both + and * operations result in a new tuple.

ANKUR 8
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON

Example :
# Concatenation
print((1, 2, 3) + (4, 5, 6)) # Output: (1, 2, 3, 4, 5, 6)

# Repeat
print(("Repeat",) * 3) # Output: ('Repeat', 'Repeat', 'Repeat')

Deleting a Tuple
 As discussed above, we cannot change the elements in a tuple.
 It means that we cannot delete or remove items from a tuple.
 Deleting a tuple entirely, however, is possible using the keyword del.
Example :
# Deleting tuples
my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

# can't delete items


del my_tuple[3] # Output: TypeError: 'tuple' object doesn't support item deletion

# Can delete an entire tuple


del my_tuple
print(my_tuple) # Output: NameError: name 'my_tuple' is not defined

Access Tuple Elements


 We can use the index operator [ ] to access an item in a tuple, where the index starts from 0.
 So, a tuple having 6 elements will have indices from 0 to 5.
 Trying to access an index outside of the tuple index range(6,7,... in this example) will raise
an IndexError.
 The index must be an integer, so we cannot use float or other types. This will result in
TypeError.
 Likewise, nested tuples are accessed using nested indexing, as shown in the example below.
Example :
# Accessing tuple elements using indexing
my_tuple = ('p','e','r','m','i','t')
print(my_tuple[0]) # Output: 'p'
print(my_tuple[5]) # Output: 't'

ANKUR 9
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON

print(my_tuple[6]) # Output: IndexError: list index out of range

# Index must be an integer


my_tuple[2.0] # Output: TypeError: list indices must be integers, not float

# nested tuple
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(n_tuple[0][3]) # Output: 's'
print(n_tuple[1][1]) # Output: 4

 Python allows negative indexing for its sequences.


 The index of -1 refers to the last item, -2 to the second last item and so on.
Example :
# Negative indexing for accessing tuple elements
my_tuple = ('p', 'e', 'r', 'm', 'i', 't')
print(my_tuple[-1]) # Output: 't'
print(my_tuple[-6]) # Output: 'p'

Tuple Operations
 Like string, tuple objects are also a sequence. Hence, the operators used with strings are also
available for the tuple.
Operator Example
The + operator returns a tuple containing all the >>> t1=(1,2,3)
elements of the first and the second tuple object. >>> t2=(4,5,6)
>>> t1+t2
(1, 2, 3, 4, 5, 6)
>>> t2+(7,)
(4, 5, 6, 7)
The * operator Concatenates multiple copies of the >>> t1=(1,2,3)
same tuple >>> t1*4
(1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3)
The [] operator Returns the item at the given index. >>> t1=(1,2,3,4,5,6)
A negative index counts the position from the right >>> t1[3]
side. 4
>>> t1[-2]
5

ANKUR 10
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON

The [:] operator returns the items in the range specified >>> t1=(1,2,3,4,5,6)
by two index operands separated by the : symbol. >>> t1[1:3]
If the first operand is omitted, the range starts from (2, 3)
zero. >>> t1[3:]
If the second operand is omitted, the range goes up to (4, 5, 6)
the end of the tuple. >>> t1[:3]
(1, 2, 3)
The in operator returns true if an item exists in the >>> t1=(1,2,3,4,5,6)
given tuple. >>> 5 in t1
True
>>> 10 in t1
False
The not in operator returns true if an item does not exist >>> t1=(1,2,3,4,5,6)
in the given tuple. >>> 4 not in t1
False
>>> 10 not in t1
True

Tuple Methods
 Methods that add items or remove items are not available with tuple.
 Only the following two methods named as count() and index() are available.
Example :
my_tuple = ('a', 'p', 'p', 'l', 'e',)
print(my_tuple.count('p')) # Output: 2
print(my_tuple.index('l')) # Output: 3

Iterating Through a Tuple


 We can use a for loop to iterate through each item in a tuple.
Example :
# Using a for loop to iterate through a tuple
for name in ('Daksh', 'Naksh'):
print("Hello", name)

Output :
Hello Daksh
Hello Naksh

ANKUR 11
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON

Tuple Membership Test


 We can test if an item exists in a tuple or not, using the keyword in.
# Membership test in tuple
my_tuple = ('a', 'p', 'p', 'l', 'e',)

# In operation
print('a' in my_tuple) # Output: True
print('b' in my_tuple) # Output: False

# Not in operation
print('g' not in my_tuple) # Output:True

List vs tuple python


SN List Tuple
1 The literal syntax of list is shown by the []. The literal syntax of the tuple is shown by
the ().
2 The List is mutable means you can add The tuple is immutable means you can’t
elements. change elements.
3 The list provides more functionality than a The tuple provides less functionality than
tuple. the list.
4 The list is used in the scenario in which we The tuple is used in the cases where we
need to store the simple collections with no need to store the read-only collections i.e.,
constraints where the value of the items the value of the items cannot be changed.
can be changed.
5 The lists are less memory efficient than a The tuples are more memory efficient
tuple. because of its immutability.

ANKUR 12
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON

File in python
 There are two types of files in Python named as Binary file and Text file
 Most importantly there are 4 types of operations that can be handled by Python on files as
Open, Read, Write, Close.
 Other operations on file include Rename and Delete.

Create a New File or Open a File


 To create a new file in Python, use the open() method.
 The open() function takes two parameters : filename and mode.
 There are four different methods (modes) for opening a file:
 "r" - Read - Default value. Opens a file for reading, error if the file does not exist
 "a" - Append - Opens a file for appending, creates the file if it does not exist
 "w" - Write - Opens a file for writing, creates the file if it does not exist
 "x" - Create - Creates the specified file, returns an error if the file exists

 In addition you can specify if the file should be handled as binary or text mode
 "t" - Text - Default value. Text mode
 "b" - Binary - Binary mode (e.g. images)

Example :
# Create a new file called "myfile.txt":
f = open("myfile.txt", "x")

Example :
# Create a new file if it does not exist:
f = open("myfile.txt", "w")

Open a File for Reading


 Assume we have the file named as demofile.txt which is located in the same folder as
Python.
 To open the file, we use the built-in open() function which has a read() method for
reading the content of the file:
Example :
f = open("demofile.txt", "r")
print(f.read())

ANKUR 13
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON

 If the file is located in a different location, you will have to specify the file path, like this:
Example :
# Open a file on a different location:
f = open("D:\\myfiles\welcome.txt", "r")
print(f.read())

 By default the read() method returns the whole text, but you can also specify how many
characters you want to return:
Example :
# Return the 5 first characters of the file:
f = open("demofile.txt", "r")
print(f.read(5))

 You can return one line by using the readline() method:


Example :
# Read one line of the file:
f = open("demofile.txt", "r")
print(f.readline())

 By calling readline() two times, you can read the two first lines:
Example :
# Read two lines of the file:
f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())

Close Files
 It is a good practice to always close the file when you are done with it.

Example :
# Close the file when you are finish with it:
f = open("demofile.txt", "r")
f.close()

ANKUR 14
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON

Write to an Existing File


 To write to an existing file, you must add a parameter to the open() function:
 "a" - Append - will append to the end of the file
 "w" - Write - will overwrite any existing content

Example :
# Open the file "demofile2.txt" and append content to the file:
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

# Open and read the file after the appending:


f = open("demofile2.txt", "r")
print(f.read())

Example :
# Open the file "demofile3.txt" and overwrite the content:
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()

# Open and read the file after the appending:


f = open("demofile3.txt", "r")
print(f.read())

Delete a File
 To delete a file, you must import the OS module, and run its os.remove() function:

Example :
# Remove the file "demofile.txt":
import os
os.remove("demofile.txt")

ANKUR 15
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON

Classes and object with self parameter in


python
 Python is an object oriented programming language.
 Almost everything in Python is an object, with its properties and methods.
 A Class is like an object constructor, or a "blueprint" for creating objects.
 Like function definitions begin with the def keyword in Python, class definitions begin with a
class keyword.
 The first string inside the class is called docstring and has a brief description of the class and
defined between ‘ ’ ’ ‘ ’ ’. Although not mandatory, this is highly recommended.
 Class Definition Syntax :
class ClassName :
# Statement-1
.
.
.
# Statement-N

 Consider the following example to create a class Employee which contains two fields as
Employee id, and name.
 The class also contains a function display(), which is used to display the information of the
Employee.
 Here, the self is used as a reference variable, which refers to the current class object.
Example :
class Employee :
id = 1
name = "Daksh"
def display (self):
print(self.id,self.name)

Object in Python
 An Object is an instance of a Class.
 A class is like a blueprint while an instance is a copy of the class
 The syntax for creating object is : object name = class name
 The procedure to create an object is : daksh = Employee()
 This will create a new object instance named daksh and we can access the attributes of
objects using the object name prefix.

ANKUR 16
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON

Example :
class Employee:
id = 1
name = "Daksh"

def display (self):


print("ID: %d \nName: %s"%(self.id,self.name))

# Creating a emp instance of Employee class


emp = Employee()
emp.display()

output :
ID: 1
Name: Daksh

Self parameter in Python


 The self parameter is a reference to the current instance of the class, and is used to access
variables that belongs to the class.
 It does not have to be named self , you can call it whatever you like, but it has to be the first
parameter of any function in the class:
Example
# Use the words mysillyobject and abc instead of self:
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age

def myfunc(abc):
print("Hello my name is " + abc.name)

p1 = Person("Daksh", 10)
p1.myfunc()

ANKUR 17
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON

The __init__ () in Python


 Class functions that begin with double underscore __ are called special functions as they
have special meaning.
 The __init__() function gets called whenever a new object of that class is instantiated.
 This type of function is also called constructors in Object Oriented Programming (OOP).
 We normally use it to initialize all the variables..
 It accepts the self-keyword as a first argument which allows accessing the attributes or
method of the class.
 We can pass any number of arguments at the time of creating the class object, depending
upon the __init__() definition.

Example : Python Program to initialize the Employee class attributes.


class Employee:
def __init__(self, name, id):
self.id = id
self.name = name

def display(self):
print("ID: %d \nName: %s" % (self.id, self.name))

emp1 = Employee("Daksh", 101)


emp2 = Employee("Naksh", 102)

# accessing display() method to print employee 1 information


emp1.display()

# accessing display() method to print employee 2 information


emp2.display()

Output :
ID: 101
Name: Daksh
ID: 102
Name: Naksh

ANKUR 18
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON

Example : Python Program of print name.


# A Sample class with init method
class Person:

# init method or constructor


def __init__(self, name):
self.name = name

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

p = Person(Daksh)
p.say_hi()

Output :
Hello, my name is Daksh

ANKUR 19
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON

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.
 In inheritance, the child class acquires all the data members, properties, and functions from
the parent class. Also, a child class can also provide its specific implementation to the
methods of the parent class.
 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.
 The basic syntax of inheritance is define as below:
class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived class

 In Python, based upon the number of child and parent classes involved, there are four types
of inheritance named as Single inheritance, Multiple Inheritance, Multilevel inheritance and
Hierarchical Inheritance.

1. Single Inheritance
 In single inheritance, a child class inherits from a single-parent class. Here is one child class
and one parent class.

ANKUR 20
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON

Example of Single inheritance :


# 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()

Output :
Inside Vehicle class
Inside Car class

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

ANKUR 21
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON

Example of Multiple inheritance :


# 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)

# 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('Daksh', 28)
emp.company_info('Google', 'Atlanta')
emp.Employee_info(12000, 'Machine Learning')

Output :
Inside Person class
Name: Daksh Age: 28

Inside Company class


Name: Google location: Atlanta

ANKUR 22
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON

Inside Employee class


Salary: 12000 Skill: Machine Learning

 In the above example, we created two parent classes Person and Company respectively.
 Then we create one child called Employee which inherit from Person and Company classes.

3. 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 of Multilevel inheritance :


# 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')

ANKUR 23
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON

# Child class
class SportsCar(Car):
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 :
Inside Vehicle class
Inside Car class
Inside SportsCar class

 In the above example, we can see there are three classes named Vehicle, Car, SportsCar.
 Vehicle is the superclass, Car is a child of Vehicle, SportsCar is a child of Car. So we can see
the chaining of classes.

4. 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.

ANKUR 24
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON

Example of Hierarchical inheritance :


# Parent class
class Vehicle:
def info(self):
print("This is Vehicle")

# Child class
class Car(Vehicle):
def car_info(self, name):
print("Car name is:", name)

# Child class
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')

Output :
This is Vehicle
Car name is: BMW

This is Vehicle
Truck name is: Ford

 In above example, we declare ‘Vehicle’ as a parent class and two child class ‘Car’ and
‘Truck’

ANKUR 25
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON

Encapsulation in Python
 Encapsulation in Python describes the concept of bindling data and methods within a single
unit.
 A class is an example of encapsulation as it binds all the data members (instance variables)
and methods into a single unit.
 Encapsulation is a way to can restrict access to methods and variables from outside of class.

 In below example, we create an Employee class by defining employee attributes such as


name and salary as an instance variable and implementing behavior using work() and show()
instance methods.

Example :
class Employee:
# constructor
def __init__(self, name, salary, project):
# data members
self.name = name
self.salary = salary
self.project = project

ANKUR 26
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON

# method to display employee's details


def show(self):
print("Name: ", self.name, 'Salary:', self.salary)

def work(self):
print(self.name, 'is working on', self.project)

# creating object of a class


emp = Employee(‘Daksh’, 8000, 'NLP')

# calling public method of the class


emp.show()
emp.work()

Output :
Name: Daksh Salary: 8000
Daksh is working on NLP

 Using encapsulation, we can hide an object’s internal representation from the outside which
is called information hiding.

Access Modifiers in Python


 Encapsulation can be achieved by declaring the data members and methods of a class either
as private or protected.
 But In Python, we don’t have direct access modifiers like public, private, and protected.
 We can achieve this by using single underscore and double underscores

 Access modifiers limit access to the variables and methods of a class.


 Python provides three types of access modifiers private, public, and protected.
 Public Member: Accessible anywhere from outside of class.
 Private Member: Accessible within the class
 Protected Member: Accessible within the class and its sub-classes

ANKUR 27
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON

Advantages of Encapsulation
 Security : The main advantage of using encapsulation is the security of the data.
Encapsulation protects an object from unauthorized access. It allows private and
protected access levels to prevent accidental data modification.

 Data Hiding : The user would not be knowing what is going on behind the scene. They
would only be knowing that to modify a data member, call the setter method. To read a
data member, call the getter method. What these setter and getter methods are doing is
hidden from them.

 Simplicity : It simplifies the maintenance of the application by keeping classes separated


and preventing them from tightly coupling with each other.

 Aesthetics : Bundling data and methods within a class makes code more readable and
maintainable.

ANKUR 28
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON

polymorphism in python
 Polymorphism in Python is the ability of an object to take many forms.
 In simple words, Polymorphism allows us to perform the same action in many different
ways.
 For example, Jessa acts as an employee when she is at the office. However, when she is at
home, she acts like a wife. Also, she represents herself differently in different places.
Therefore, the same person takes different forms as per the situation.

 In polymorphism, a method can process objects differently depending on the class type or
data type.
 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.
 The len() method treats an object as per its class type.

Example :
students = ['Emma', 'Jessa', 'Kelly']
school = 'ABC School'

# calculate count
print(len(students)) #output : 3
print(len(school)) #output : 10

ANKUR 29
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON

Example :
class Vehicle:

def __init__(self, name, color, price):


self.name = name
self.color = color
self.price = price

def show(self):
print('Details:', self.name, self.color, self.price)

def max_speed(self):
print('Vehicle max speed is 150')

def change_gear(self):
print('Vehicle change 6 gear')

ANKUR 30
L.J. GANDHI BCA COLLEGE, MODASA UNIT : 3 BCA-601-PYTHON

# inherit from vehicle class


class Car(Vehicle):
def max_speed(self):
print('Car max speed is 240')

def change_gear(self):
print('Car change 7 gear')

# Car Object
car = Car('Car x1', 'Red', 20000)
car.show()

# calls methods from Car class


car.max_speed()
car.change_gear()

# Vehicle Object
vehicle = Vehicle('Truck x1', 'white', 75000)
vehicle.show()

# calls method from a Vehicle class


vehicle.max_speed()
vehicle.change_gear()

Output :
Details: Car x1 Red 20000
Car max speed is 240
Car change 7 gear

Details: Truck x1 white 75000


Vehicle max speed is 150
Vehicle change 6 gear

ANKUR 31

You might also like