0% found this document useful (0 votes)
3 views24 pages

Presentation 5

Uploaded by

bnhatm216
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)
3 views24 pages

Presentation 5

Uploaded by

bnhatm216
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/ 24

Python Introduction

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)

• function: A function to apply to each element of the iterable.


• iterable: An iterable (e.g., list, tuple, etc.) whose elements the function will be applied to.

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.

Destructor is used to perform the clean-up activity before destroying the


object, such as closing database connections or filehandle.

Tasks performed by the destructor:

• open files,
• database connections,
• cleaning up the buffer or cache
Python Introduction
Python OOPs Concepts
Python Destructors to Destroy the Object

destructor gets called in the following two cases

• When an object goes out of scope (End of a function, End of block)


• The reference counter of the object reaches 0.

In Python, The special method __del__() is used to define a


destructor.
Python Introduction
Python OOPs Concepts
Python Destructors to Destroy the Object
Create Destructor using the __del__() Method
Syntax of destructor declaration
def __del__(self): # body of a destructor

def: The keyword is used to define a method.


__del__() Method: It is a reserved method. This method gets called as soon as all references to the
object have been deleted
self: The first argument self refers to the current object.
Python Introduction
Python OOPs Concepts
Python Destructors to Destroy the Object
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('Emma')
s1.show()

# delete object
del s1
Python Introduction
Python OOPs Concepts
Python Destructors to Destroy the Object

Important Points to Remember about Destructor


• The __del__ method is called for any object when the reference count for that object becomes zero.
• The reference count for that object becomes zero when the application ends, or we delete all references
manually using the del keyword.
• The destructor will not invoke when we delete object reference. It will only invoke when all references to the
objects get deleted.
Python Introduction
Python OOPs Concepts
Python Destructors to Destroy the Object
Important Points to Remember about Destructor
Python Introduction
Python OOPs Concepts
Python Destructors to Destroy the Object
Example import time
class Student:
# constructor
def __init__(self, name):
print('Inside Constructor')
self.name = name
def show(self):
print('Hello, my name is', self.name)
# destructor
def __del__(self):
print('Object destroyed')
# create object
s1 = Student('Emma')
# create new reference
# both reference points to the same object
s2 = s1
s1.show()
# delete object reference s1
del s1
# add sleep and observe the output
time.sleep(5)
print('After sleep')
s2.show()
Python Introduction
Python OOPs Concepts
Python Destructors to Destroy the Object
Cases when Destructor doesn’t work Correctly
1. Circular referencing when two objects refer to each other
2. Exception occured in __init__() method

1. Circular referencing when two objects refer to each other

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.

A class is an example of encapsulation as it binds all the data members (instance


variables) and methods into a single unit.
Python Introduction
Python OOPs Concepts
Encapsulation in Python

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 # calling public method of the class


# to display employee's details emp.show()
def show(self): emp.work()
# accessing public data member
print("Name: ", self.name, 'Salary:', self.salary)

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

• Public Member: Accessible anywhere from outside class.


• Private Member: Accessible within the class
• Protected Member: Accessible within the class and its sub-classes
Python Introduction
Python OOPs Concepts
Encapsulation in Python
Access Modifiers in Python
Public Member
Public data members are accessible within and outside of a class. All
member variables of the class are by default public.
Example

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

# creating object of a class


emp = Employee('Jessa', 10000)

# accessing private data members


print('Salary:', emp.__salary)
Python Introduction
Python OOPs Concepts
Encapsulation in Python
Access Modifiers in Python
Private Member

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)

# calling public method of the class


emp. public_show()
Python Introduction
Python OOPs Concepts
Encapsulation in Python
Access Modifiers in Python

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 getters and setters methods are often used when:


• When we want to avoid direct access to private variables # Setter for 'age'
def set_age(self, age):
• To add validation logic for setting a value class Person:
if age > 0: # Validation to ensure age is positive
def __init__(self, name, age): self._age = age
self._name = name # private attribute else:
• When we want to avoid direct access to private variables self._age = age # private attribute
print("Age must be positive.")
# Getter for 'name'
def get_name(self): # Usage
return self._name person = Person("Alice", 30)
# Setter for 'name' print(person.get_name()) # Alice
def set_name(self, name): person.set_name("Bob")
self._name = name print(person.get_name()) # Bob
# Getter for 'age' person.set_age(-5) # Invalid age
def get_age(self):
return self._age
Python Introduction
Python OOPs Concepts
Encapsulation in Python
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.
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.

In polymorphism, a method can process objects


differently depending on the class type or data type.
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

students = ['Emma', 'Jessa', 'Kelly']


school = 'ABC School'

# 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

You might also like