Presentation 5
Presentation 5
map() Function:
The map() function applies a given function to all items in an iterable (e.g., list, tuple) and
returns an iterator (map object) of the results.
Syntax
map(function, iterable)
def square(x):
return x * x
numbers = [1, 2, 3, 4, 5] numbers = [1, 2, 3, 4, 5]
result = map(square, numbers) result = map(lambda x: x * x, numbers)
print(list(result)) # Output: [1, 4, 9, 16, 25] print(list(result)) # Output: [1, 4, 9, 16, 25]
Python Introduction
Python OOPs Concepts
Python Destructors to Destroy the Object
Destructor
Destructor is a special method that is called when an object gets destroyed.
• open files,
• database connections,
• cleaning up the buffer or cache
Python Introduction
Python OOPs Concepts
Python Destructors to Destroy the Object
# delete object
del s1
Python Introduction
Python OOPs Concepts
Python Destructors to Destroy the Object
When both objects go out of scope, Python doesn’t know which object to destroy first.
So, to avoid any errors, it doesn’t destroy any of them.
Python Introduction
Python OOPs Concepts
1. Circular referencing when two objects refer to each other
Example
import time
class Vehicle(): # create car object
def __init__(self, id, car):
c = Car(12)
self.id = id;
# saving reference of Car object # delete car object
self.dealer = car; del c
print('Vehicle', self.id, 'created'); # ideally destructor must execute now
def __del__(self): # to observe the behavior
print('Vehicle', self.id, 'destroyed'); time.sleep(8)
class Car():
def __init__(self, id):
self.id = id;
# saving Vehicle class object in 'dealer' variable
# Sending reference of Car object ('self') for Vehicle object
self.dealer = Vehicle(id, self);
print('Car', self.id, 'created')
def __del__(self):
print('Car', self.id, 'destroyed')
Python Introduction
Python OOPs Concepts
Python Destructors to Destroy the Object
2. Exception occured in __init__() method
Likewise, in Python, if any exception occurs in the init method while initializing the
object, the method del gets called. But actually, an object is not created
successfully, and resources are not allocated to it
class Vehicle:
def __init__(self, speed):
if speed > 240:
raise Exception('Not Allowed');
self.speed = speed;
def __del__(self):
print('Release resources')
# creating an object
car = Vehicle(350);
# to delete the object explicitly
del car
Python Introduction
Python OOPs Concepts
Encapsulation in Python
Encapsulation in Python describes the concept of bundling data and methods within a single unit.
Example
class Employee:
# constructor
def __init__(self, name, salary, project):
# data members
self.name = name
self.salary = salary # creating object of a class
self.project = project emp = Employee('Jessa', 8000, 'NLP')
# method
def work(self):
print(self.name, 'is working on', self.project)
Python Introduction
Python OOPs Concepts
Encapsulation in Python
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. But in python we are using single underscore and double underscores.
Python provides three types of access modifiers private, public, and protected.
class MyClass:
def __init__(self, value):
self.value = value # public attribute
def show(self):
print(f"Value is {self.value}") # public method
obj = MyClass(10)
print(obj.value) # Accessing public attribute
obj.show() # Calling public method
Python Introduction
Python OOPs Concepts
Encapsulation in Python
Access Modifiers in Python
Private Member
We can protect variables in the class by marking them private. To define a
private variable add two underscores as a prefix at the start of a variable name.
Example Private members are accessible only within the class, and we can’t
access them directly from the class objects.
class Employee:
# constructor
def __init__(self, name, salary):
# public data member
self.name = name
# private member
self.__salary = salary
We can access private members from outside of a class using the following two approaches
• Create public method to access private members
class Employee:
• Use name mangling # constructor
def __init__(self, name, salary):
• Create public method to access private members: # public data member
Access Private member outside of a class using an self.name = name
# private member
instance method self.__salary = salary
# public instance methods
def public_show(self):
# private members are accessible from a class
print("Name: ", self.name, 'Salary:', self.__salary)
# creating object of a class
emp = Employee('Jessa', 10000)
Private Member
We can access private members from outside of a class using the following two approaches
• Create public method to access private members
• Use name mangling class Employee:
# constructor
Name Mangling to access private members: def __init__(self, name, salary):
The name mangling is created on an identifier by adding # public data member
self.name = name
two leading underscores and one trailing underscore, # private member
like this _classname__dataMember, where classname is self.__salary = salary
the current class, and data member is the private # creating object of a class
variable name. emp = Employee('Jessa', 10000)
print('Name:', emp.name)
# direct access to private member using name mangling
print('Salary:', emp._Employee__salary)
Python Introduction
Python OOPs Concepts
Encapsulation in Python
Access Modifiers in Python
Protected Member
Protected members are accessible within the class and also available to its sub-classes. To define a
protected member, prefix the member name with a single underscore _.
class MyClass:
Protected data members are used when you def __init__(self, value):
self._value = value # protected attribute
implement inheritance and want to allow data members
access to only child classes. def _show(self):
print(f"Value is {self._value}") # protected method
class SubClass(MyClass):
def display(self):
print(f"Value in subclass is {self._value}") # Accessing protected member in subclass
obj = SubClass(20)
obj.display() # Calling method in subclass
obj._show() # Accessing protected method from outside (not recommended)
Python Introduction
Python OOPs Concepts
Encapsulation in Python
Getters and Setters in Python In Python, getter and setter methods are used to access and modify the attributes of a class.
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.
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.
class Student:
The getters and setters methods are often used when: def __init__(self, name, roll_no, age):
# private member
• Information Hiding and conditional logic for setting an object attributes self.name = name
# private members to restrict access
# avoid direct data modification
self.__roll_no = roll_no
jessa = Student('Jessa', 10, 15) self.__age = age
def show(self):
# before Modify print('Student Details:', self.name, self.__roll_no)
jessa.show() # getter methods
# changing roll number using setter def get_roll_no(self):
jessa.set_roll_no(120) return self.__roll_no
jessa.set_roll_no(25) # setter method to modify data member
jessa.show() # condition to allow data modification with rules
def set_roll_no(self, number):
if number > 50:
print('Invalid roll no. Please set correct roll number')
else:
self.__roll_no = number
Python Introduction
Python OOPs Concepts
Polymorphism in Python
Polymorphism
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.
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
# calculate count
print(len(students))
print(len(school))
Python Introduction
Python OOPs Concepts
Polymorphism in Python
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