0% found this document useful (0 votes)
24 views15 pages

Unit 2

Python supports object-oriented programming through the use of objects and classes. An object has attributes and behaviors, while a class acts as a blueprint for the object. Key concepts of OOP in Python include inheritance, encapsulation, polymorphism, and abstraction. Inheritance allows a child class to inherit attributes and behaviors from a parent class. Encapsulation bundles attributes and methods within a class. Polymorphism allows the same interface for different objects. Python also supports other programming paradigms like procedural and functional through the use of functions, generators, lambda functions, and built-in functions like map and filter.

Uploaded by

Harsh Kumar
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)
24 views15 pages

Unit 2

Python supports object-oriented programming through the use of objects and classes. An object has attributes and behaviors, while a class acts as a blueprint for the object. Key concepts of OOP in Python include inheritance, encapsulation, polymorphism, and abstraction. Inheritance allows a child class to inherit attributes and behaviors from a parent class. Encapsulation bundles attributes and methods within a class. Polymorphism allows the same interface for different objects. Python also supports other programming paradigms like procedural and functional through the use of functions, generators, lambda functions, and built-in functions like map and filter.

Uploaded by

Harsh Kumar
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/ 15

Unit-2

Python Object oriented programming


Python Object Oriented Programming
• Python is a versatile programming language that supports various
programming styles, including
object-oriented programming (OOP) through the use of objects and classes.
• An object is any entity that has attributes and behaviors.

For example, a parrot is an object. It has


•attributes - name, age, color, etc.
•behavior - dancing, singing, etc.
Similarly, a class is a blueprint for that object.
I can eat! I can sleep! I can bark! Woof woof!!
I can eat! I can sleep! I can bark! Woof woof!!

In the above example, we created a class with the name Parrot with two attributes: name and age.
we created instances of the Parrot class. Here, parrot1 and parrot2 are references (value) to our new objects.
We then accessed and assigned different values to the instance attributes using the objects name and
the notation.

• Python Inheritance
• Inheritance is a way of creating a new class for using details of an existing class without
modifying it.
• The newly formed class is a derived class (or child class). Similarly, the existing class is a base
class (or parent class).
The output of the below code snippet is:
Here, dog1 (the object of derived class Dog) can access members of the base class Animal.
It's because Dog is inherited from Animal.
Python Encapsulation
Encapsulation is one of the key features of object-oriented programming. Encapsulation
refers to the bundling of attributes and methods inside a single class.
It prevents outer classes from accessing and changing attributes and methods of a class.
This also helps to achieve data hiding.
In Python, we denote private attributes using underscore as the prefix i.e single _ or
double __. For example,
In the above program, we defined a Computer class.
We used __init__() method to store the maximum selling price of Computer. notice in the code.
we have tried to modify the value of __maxprice outside of the class. However, since __maxprice is a private variable, this
modification is not seen on the output. c.__maxprice = 1000
As shown, to change the value, we have to use a setter function i.e setMaxPrice() which takes price as a parameter.

• Polymorphism
• Polymorphism is another important concept of object-oriented programming. It simply means more than one
form.
• That is, the same entity (method or operator or object) can perform different operations in different scenarios.
• Let's see an example, in next slide

Key Points to Remember:


•Object-Oriented Programming makes the program easy to understand as well as efficient.
•Since the class is sharable, the code can be reused.
•Data is safe and secure with data abstraction.
•Polymorphism allows the same interface for different objects, so programmers can write efficient code.
The output is:
Rendering Square
Rendering Circle
In the above example, we have created a superclass: Polygon and two subclasses: Square and Circle.
Notice the use of the render() method.
The main purpose of the render() method is to render the shape.
However, the process of rendering a square is different from the process of rendering a circle.
Hence, the render() method behaves differently in different classes. Or, we can say render() is polymorphic.

Python Classes
• A class is considered as a blueprint of objects. We can think of the class as a sketch (prototype) of a house. It
contains all the details about the floors, doors, windows, etc. Based on these descriptions we build the house.
House is the object.
• Since many houses can be made from the same description, we can create many objects from a class.
Python Objects
An object is called an instance of a class. For example, suppose Bike is a class then we can create objects
like bike1, bike2, etc from the class.
Here's the syntax to create an object. Now, we can use this object to access the class attributes.

#create class class Bike:


name = ""
gear = 0
# create objects of clas
s bike1 = Bike()
Python Iterators
Iterators are methods that iterate collections like lists, tuples, etc. Using an iterator
method, we can loop through an object and return its elements.
Technically, a Python iterator object must implement two special
methods, __iter__() and __next__(), collectively called the iterator protocol.
In Python, we can use next() function to return the next item in the sequence.
Output is 4 7 0
Here, first we created an iterator from the list using the iter() method. And then used the next() function to
retrieve the elements of the iterator in sequential order.
When we reach the end and there is no more data to be returned, we will get the StopIteration Exception.

• Python Generators
• In Python, a generator is a function that returns an iterator that produces a sequence of values when iterated
over.
• Generators are useful when we want to produce a large sequence of values, but we don't want to store all of
them in memory at once.

def generator_name(arg):
# statements
yield something
we can define a generator function using the def keyword,
but instead of the return statement we use the yield statement.
• Python Lambda Function:
• Lambda function is a small anonymous function. It can take any number of arguments but can
only have single expression.
• lambda arguments : expression
• x = lambda a : a + 10
print(x(5))
• Multiply argument a with argument b and return the result:

• x = lambda a, b : a * b
print(x(5, 6))
• x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
• Why Use Lambda Functions?
• The power of lambda is better shown when you use them as an anonymous function inside
another function.
• Say you have a function definition that takes one argument, and that argument will be multiplied
with an unknown number:
• def myfunc(n):
return lambda a : a * n
map() - Python's map() method applies a specified function to each item of an iterable (such as a list, tuple, or string)
and then returns a new iterable containing the results.
The map() syntax is as follows: map(function, iterable)
The first argument passed to the map function is itself a function, and the second argument passed is an iterable (sequence of elements)
such as a list, tuple, set, string, etc.
Example 1 - usage of the map():
1.# Using map() to square each element of the data list
2.data = [1, 2, 3, 4, 5]
3.
4.# Map function returns the map object
5.squares = map(lambda x: x*x, data)
6.
7.# Iterating the elements of the squares
8.for i in squares:
9. print(i, end=" ")
10.
11.# Also, we can convert the map object into a list
12.squares = list(map(lambda x: x*x, data))
13.print(f"Squares: {squares}")
Output:
1, 4, 9, 16, 25 Squares: [1, 4, 9, 16, 25]
Here, the map function takes each element one by one from the data starting from x = 1.
Each element is passed to the lambda function, returning its square.
And the returned value is stored in the map object (an iterable).
• filter() - The filter() function in Python filters elements from an
iterable based on a given condition or function and returns a new
iterable with the filtered elements.
• The syntax for the filter() is as follows: filter(function, iterable)
• Here also, the first argument passed to the filter function is itself a
function, and the second argument passed is an iterable (sequence of
elements) such as a list, tuple, set, string, etc.
• Example 1 - usage of the filter():
• You are given a list of integers and should filter the even numbers
from the list.

1.# Using filter() to filter even numbers from a list
2.data = [1, 2, 3, 4, 5]
3.
4.# The filter function filters the even numbers from the data
5.# and returns a filter object (an iterable)
6.evens = filter(lambda x: x % 2 == 0, data)
7.
8.# Iterating the values of evens
9.for i in evens:
10. print(i, end=" ")
11.
12.# We can convert the filter object into a list as follows:
13.evens = list(filter(lambda x: x % 2 == 0, data))
14.
15.# Printing the evens list
16.print(f"Evens = {evens}")

You might also like