0 - Unit-V OOP - Python Libraries
0 - Unit-V OOP - Python Libraries
sound attribute is a class attribute. It is shared across all instances of Dog class,
so can be directly accessed through instance dog1.
CLASS CONSTRUCTOR USING _ _INIT_ _() FUNCTION
In Python, class has __init__() function. It automatically initializes object attributes when
an object is created.
class Dog:
species = "Canine" # Class attribute
def bark(self):
print(f"{self.name} is barking!")
def __str__(self):
return f"{self.name} is {self.age} years old." # Correct: Returning a string
dog1 = Dog("Buddy", 3)
dog2 = Dog("Charlie", 5)
#output
print(dog1) Buddy is 3 years old.
print(dog2) Charlie is 5 years old.
CLASS METHODS
Methods are the functions we use to describe the behavior of objects. They are
also defined inside a class.
class Car:
car_type = "Sedan"
def __init__(self, name, mileage):
self.name = name
self.mileage = mileage
def description(self):
return f“The {self.name} car gives the mileage of {self.mileage}km/l“
def max_speed(self, speed):
return f"The {self.name} runs at the maximum speed of {speed}km/hr"
obj2 = Car("Honda City",24.1)
print(obj2.description())
print(obj2.max_speed(150))
We know the methods defined inside a class, other than the constructor method, as instance methods.
Furthermore, we have two instance methods here – description() and max_speed().
description()- This method returns a string with the description of the car, such as the name and its
mileage. This method has no additional parameter. This method uses instance attributes.
max_speed()- This method has one additional parameter and returns a string displaying the car’s
name and speed
Note: Three important things to remember are-
You can create any number of objects in a class.
If the method requires n parameters and you do not pass the same number of arguments, then an
error will occur.
The order of the arguments matters.
MESSAGE PASSING
Message passing is how objects talk to each other in object-oriented programming. One object sends a message (calls a method) to another object to
make it do something or to get some information.
class Car:
def __init__(self, brand):
self.brand = brand
def start_engine(self):
print(f"The {self.brand} engine has started.")
class Driver:
def __init__(self, name):
self.name = name
Instance Variables
Variables that are unique to each instance (object) of a class. These are defined within __init__
method or other instance methods. Each object maintains its own copy of instance variables,
independent of other objects.
class Dog: # Access Class and Instance Variables
# Class variable print(dog1.species) #(class variable)
species = "Canine“ print(dog1.name) #(instance variable)
print(dog1.age) # (instance variable)
def __init__(self, name, age): # Modify instance variables
# Instance variables dog1.name = “Max”
self.name = name print(dog1.name) #(updated instance V)
self.age = age # Modify Class Variable
Dog.species = “Feline”
# Create objects print(dog1.species) #(updated class variable)
dog1 = Dog("Buddy", 3) print(dog2.species)
dog2 = Dog("Charlie", 5)
Ouput
Canine
Buddy
Charlie
Max
Feline
Feline
Class Variable (species): Shared by all instances of the class. Changing Dog.species affects all objects,
as it’s a property of the class itself.
Instance Variables (name, age): Defined in the __init__ method. Unique to each instance (e.g.,
dog1.name and dog2.name are different).
Accessing Variables: Class variables can be accessed via the class name (Dog.species) or an object
(dog1.species). Instance variables are accessed via the object (dog1.name).
Updating Variables: Changing Dog.species affects all instances. Changing dog1.name only affects
dog1 and does not impact dog2.
INHERITANCE IN PYTHON
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a
class (called a child or derived class) to inherit attributes and methods from another class
(called a parent or base class). This promotes code reuse, modularity, and a hierarchical class
structure.
Inheritance allows us to define a class that inherits all the methods and properties from
another class.
Syntax for Inheritance
class ParentClass:
# Parent class code here
pass
class ChildClass(ParentClass):
# Child class code here
pass
Parent Class:
This is the base class from which other classes inherit.
It contains attributes and methods that the child class can reuse.
Child Class:
This is the derived class that inherits from the parent class.
The syntax for inheritance is class ChildClass (ParentClass).
The child class automatically gets all attributes and methods of the
parent class unless overridden.
# Parent class
class Animal:
def __init__(self, name):
self.name = name # Initialize the name attribute
def speak(self):
pass # Placeholder method to be overridden by child classes
# Constructor
def __init__(self, name, id):
self.name = name
self.id = id
# 1. Single Inheritance
class Person:
def __init__(self, name):
self.name = name
class Employee(Person): # Employee inherits from Person
def __init__(self, name, salary):
super().__init__(name)
self.salary = salary
# 2. Multiple Inheritance
class Job:
def __init__(self, salary):
self.salary = salary
class EmployeePersonJob(Employee, Job): # Inherits from both Employee and Job
def __init__(self, name, salary):
Employee.__init__(self, name, salary) # Initialize Employee
Job.__init__(self, salary) # Initialize Job
# 3. Multilevel Inheritance
class Manager(EmployeePersonJob): # Inherits from EmployeePersonJob
def __init__(self, name, salary, department):
EmployeePersonJob.__init__(self, name, salary) # Explicitly initialize EmployeePersonJob
self.department = department
# 4. Hierarchical Inheritance
class AssistantManager(EmployeePersonJob): # Inherits from EmployeePersonJob
def __init__(self, name, salary, team_size):
EmployeePersonJob.__init__(self, name, salary) # Explicitly initialize EmployeePersonJob
self.team_size = team_size
# Polymorphic behavior
animals = [Dog(), Cat(), Animal()]
for animal in animals:
print(animal.sound()) # Calls the overridden method based on the object type
DATA ABSTRACTION IN PYTHON
Data abstraction is one of the most essential concepts of Python OOPs which is used to hide irrelevant
details from the user and show the details that are relevant to the users.
A simple example of this can be a car. A car has an accelerator, clutch, and break and we all know
that pressing an accelerator will increase the speed of the car and applying the brake can stop the
car but we don't know the internal mechanism of the car and how these functionalities can work this
detail hiding is known as data abstraction.
Data abstraction in Python is a programming concept that hides complex implementation details while
exposing only essential information and functionalities to users. In Python, we can achieve data
abstraction by using abstract classes and abstract classes can be created using abc (abstract base
class) module and abstractmethod of abc module.
ABSTRACTION CLASSES IN PYTHON
Abstract class is a class in which one or more abstract methods are defined. When a method is
declared inside the class without its implementation is known as abstract method.
Abstract Method: In Python, abstract method feature is not a default feature. To create abstract
method and abstract classes we have to import the "ABC" and "abstractmethod" classes from abc
(Abstract Base Class) library. Abstract method of base class force its child class to write the
implementation of the all abstract methods defined in base class. If we do not implement the abstract
methods of base class in the child class then our code will give error. In the below code method_1 is a
abstract method created using @abstractmethod decorator.
from abc import ABC, abstractmethod
class BaseClass(ABC):
@abstractmethod
def method_1(self):
#empty body
pass
Concrete Method: Concrete methods are the methods defined in an abstract base class with their
complete implementation. Concrete methods are required to avoid replication of code in subclasses.
For example, in abstract base class there may be a method that implementation is to be same in all its
subclasses, so we write the implementation of that method in abstract base class after which we do not
need to write implementation of the concrete method again and again in every subclass. In the below
code startEngine is a concrete method.
class Car(ABC):
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year
self.engine_started = True
def startEngine(self):
if not self.engine_started:
print(f"Starting the {self.model}'s engine.")
self.engine_started = True
else:
print("Engine is already running.")
IMPLEMENTATION OF DATA ABSTRACTION IN PYTHON
In the below code, we have implemented data abstraction using abstract class and method. Firstly, we
import the required modules or classes from abc library then we create a base class 'Car' that
inherited from 'ABC' class that we have imported. Inside base class we create init function, abstract
function and non-abstract functions. To declare abstract function printDetails we use
"@abstractmethod" decorator. After that we create child class hatchback and suv. Since, these child
classes inherited from abstract class so, we need to write the implementation of all abstract function
declared in the base class. We write the implementation of abstract method in both child class. We
create an instance of a child class and call the printDetails method. In this way we can achieve the
data abstraction.
# Import required modules # create a child class
from abc import ABC, abstractmethod class Hatchback(car):
# Create Abstract base class def PrintDetails(self):
class Car(ABC): Print(“Brand”,self.brand)
def __init__(self, brand, model, year): Print(“Model”,self.model)
self.brand = brand Print(“Year”, self.year)
self.model = model def sunroof(self):
self.year = year print(“Not having this feature”)
# Create abstract method # create a child class
@abstractmethod Class Suv(Car):
def printDetails(self): def PrintDetails(self):
pass Print(“Brand”, self.brand)
# Create concrete method Print(“Model”,self.model)
def accelerate(self): Print(“Year”, self.year)
print("Speed up ...") def sunroof(self):
def break_applied(self): print(“available”)
print("Car stopped")
# Create an instance of the Hatchback class
car1 = Hatchback("Maruti", "Alto", "2022")
# Call methods
car1.printDetails()
car1.accelerate()
car1.sunroof()
Output
Brand: Maruti
Model: Alto
Year: 2022
Speed up ...
Not having this feature
ENCAPSULATION
Encapsulation is a way to ensure security. Basically, it hides the data from the access of
outsiders. Such as, if an organization wants to protect an object/information from unwanted
access by clients or any unauthorized person, then encapsulation is the way to ensure this.
You can declare methods or attributes as protected by using a single underscore (_) before their
names, like _self.name or def _method(). Both lines indicate that the attribute and method are
protected, accessible only within the class and subclasses, but can be accessed by class methods
and objects.
Though Python uses ‘ _ ‘ just as a coding convention, it tells that you should use these
attributes/methods within the scope of the class. But you can still access the variables and
methods which are defined as protected, as usual.
Though Python uses ‘ _ ‘ just as a coding convention, it tells that you should use these
attributes/methods within the scope of the class. But you can still access the variables and
methods which are defined as protected, as usual.
Now to actually prevent the access of attributes/methods from outside the scope of a class, you
can use “private members“. In order to declare the attributes/method as private members, use
double underscore ( ) in the prefix. Such as – self.name or def __method(); Both of these lines
tell that the attribute and method are private and access is not possible from outside the class.
class car:
def __init__(self, name, mileage):
self._name = name #protected variable
self.mileage = mileage
def description(self):
return f"The {self._name} car gives the mileage of {self.mileage}km/l“
obj = car("BMW 7-series",39.53)
#accessing protected variable via class method
print(obj.description())
#accessing protected variable directly from outside
print(obj._name)
print(obj.mileage)
Let us see how encapsulation works,
class Car:
def __init__(self, name, mileage):
self.__name = name #private variable
self.mileage = mileage
def description(self):
return f"The {self.__name} car gives the mileage of {self.mileage}km/l“
# output
First Student
Name : Jessa Age : 14
NumPy library in Python
NumPy stands for Numerical Python and is one of the most useful scientific libraries in
Python programming. It provides support for large multidimensional array objects and
various tools to work with them.
Arrays are a collection of elements/values, that can have one or more dimensions. An
array of one dimension is called a Vector while having two dimensions is called a
Matrix.
NumPy arrays are called ndarray or N-dimensional arrays and they store elements of
the same type and size. It is known for its high-performance and provides efficient
storage and data operations as arrays grow in size.
Creating a NumPy Array
●NumPy arrays are very easy to create given the complex problems they solve. To create a
very basic ndarray, you use the np.array() method. All you have to pass are the values of
the array as a list:
● This array contains integer values. You can specify the type of data in the dtype argument:
● np.array([1,2,3,4],dtype=np.float32)
● Output:
● array([1., 2., 3., 4.], dtype=float32)
Since NumPy arrays can contain only homogeneous datatypes, values will be upcast if the types do not
●
match:
np.array([1,2.0,3,4])
●
Output:
●
np.array([[1,2,3,4],[5,6,7,8]])
●
array([[1, 2, 3, 4],
●
[5, 6, 7, 8]])
Here, we created a 2-dimensional array of values.
●
Note: A matrix is just a rectangular array of numbers with shape N x M where N is the number of rows
●
and M is the number of columns in the matrix. The one you just saw above is a 2 x 4 matrix.
Size of NumPy array
●You can determine how many values there are in the array using the size attribute. It
just multiplies the number of rows by the number of columns in the ndarray:
● # size of array
● a = np.array([[5,10,15],[20,25,20]])
● print('Size of array :',a.size)
● print('Manual determination of size of array :',a.shape[0]*a.shape[1])
● Size of array : 6
● Manual determination of size of array : 6
Mathematical Operations in Numpy
Addition
The add() function sums the content of two arrays, and return the results in a new array.
import numpy as np
print(newarr)
# output
[30,32,34,36,38]
Subtraction
The subtract() function subtracts the values from one array with the values from another array,
and return the results in a new array.
import numpy as np
print(newarr)
# output
This mathematical function helps user to calculate square value of each element in the array.
Parameters :
arr : [array_like] Input array or object whose elements, we need to square.
import numpy as np
Square Value of arr1 : [ 1 9 225 217156] Square Value of arr2 : [ 529 3136]
Trignometric Functions in Numpy
NumPy provides the sin(), cos() and tan() that take values in radians and produce the corresponding sin,
cos and tan values.
import numpy as np
x = np.sin(np.pi/2)
print(x)
# output
1.0
import numpy as np
x = np.sin(arr)
Comparison Operators
Comparison operators such as < , > , <= , >=, = = , ! = can be applied directly to NumPy
arrays, resulting in a boolean array indicating the truth value of the condition for each
element.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
mask = arr > 2
print(mask)
filtered_arr = arr[mask]print(filtered_arr)
# Output: [3 4 5]
# Output: [2 3 4]
Matrix Multiplication in NumPy
So, A.B = [[1*4 + 2*6, 2*4 + 3*6], [1*5 + 2*7, 2*5 + 3*7]
In Python numpy.dot() method is used to calculate the dot product between two
arrays.
Example 1 : Matrix multiplication of 2 square matrices.
# importing the module
import numpy as np
# computing product
result = np.dot(p, q)
# create a 1D array
array1 = np.array([1, 3, 5, 7, 8, 9, 2, 4, 6])
print(arr1.shape)
print(arr2.shape)
Shape of Array of Tuples
we’ll create a NumPy array where each element is a tuple. We’ll also demonstrate
how to determine the shape of such an array.
import numpy as np
Parameters:
•data: array- Contains data stored in Series.
•index: array-like or Index (1d)
•dtype: str, numpy.dtype, or ExtensionDtype, optional
•name: str, optional
•copy: bool, default False
Example 1: Series holding the char data type.
import pandas as pd
# a simple char list
list = ['g', 'e', 'e', 'k', 's']
#output
0 g
1 e
2 e
3 k
4 S
Dtype : object
Example 2: Series holding the Int data type.
import pandas as pd
#output
0 1
1 2
2 3
3 4
4 5
Dtype : int64
Example 3: Series holding the dictionary.
import pandas as pd
res = pd.Series(dic)
print(res)
#output
Id 1013
Name Sachin
State MH
Age 24
Dtype : object
Dataframe
In the real world, a Pandas DataFrame will be created by loading the datasets from existing
storage, storage can be SQL Database, CSV file, and Excel file. Pandas DataFrame can be
created from the lists, dictionary, and from a list of dictionary etc. Dataframe can be created in
different ways here are some ways by which we create a dataframe:
Example 1: DataFrame can be created using a single list or a list of lists.
# import pandas as pd
import pandas as pd
# list of strings
lst = ['Geeks', 'For', 'Geeks', 'is',
'portal', 'for', 'Geeks']
To create DataFrame from dict of narray/list, all the narray must be of same length. If index is passed then the
length index should be equal to the length of arrays. If no index is passed, then by default, index will be
range(n) where n is the array length.
import pandas as pd
# Create DataFrame
df = pd.DataFrame(data)
Selection of column: In Order to select a column in Pandas DataFrame, we can either access the columns by
calling them by their columns name.
pandas.DataFrame.loc is a function used to select rows from Pandas DataFrame based on the condition
provided.
Parameters:
•df: represents data frame
•cname: represents column name
•condition: represents condition on which rows has to be
selected
# Importing pandas as pd
from pandas import DataFrame
print("\n")
# Importing pandas as pd
from pandas import DataFrame
A panel is a 3D container of data. The term Panel data is derived from econometrics and is
partially responsible for the name pandas − pan(el)-da(ta)-s.
The names for the 3 axes are intended to give some semantic meaning to describing operations
involving panel data. They are −
pandas.Panel()
Parameter Description
Data takes various forms like
ndarray, series, map, lists, dict,
data
constants and also another
DataFrame
items axis=0
major_axis axis=1
minor_axis axis=2
dtype Data type of each column
copy Copy data. Default, false
Create Panel
From 3D ndarray
Its output is as follows −
<class 'pandas.core.panel.Panel'>
Dimensions: 0 (items) x 0 (major_axis) x 0 (minor_axis)
Items axis: None
Major_axis axis: None
Minor_axis axis: None
Selecting the Data from Panel
Using Items
# creating an empty panel
import pandas as pd
import numpy as np
data = {'Item1' : pd.DataFrame(np.random.randn(4,3)),
'Item2' : pd.DataFrame(np.random.randn(4,2))}
p = pd.Panel(data)
print(p['Item1'])
# output
0 1 2
0 0.488824 -0.128637 0.930817
1 0.417497 0.896681 0.576657
2 -2.775266 0.571668 0.290082
3 -0.400538 -0.144234 1.110535
Using major_axis
Item1 Item2
0 0.417497 0.748412
1 0.896681 -0.557322
2 0.576657 NaN
Using minor_axis
Item1 Item2
0 -0.128637 -1.047032
1 0.896681 -0.557322
2 0.571668 0.4319533
3 -0.144234 1.302466
What is Matplotlib?
Matplotlib is a low level graph plotting library in python that serves as a visualization
utility.
Matplotlib was created by John D. Hunter.
Matplotlib is open source and we can use it freely.
Matplotlib is mostly written in python, a few segments are written in C, Objective-C and
Javascript for Platform compatibility.
Matplotlib Pyplot
Pyplot
Most of the Matplotlib utilities lies under the pyplot submodule, and are usually imported under
the plt alias:
plt.plot(xpoints, ypoints)
plt.show()
Matplotlib Plotting
If we need to plot a line from (1, 3) to (8, 10), we have to pass two arrays [1, 8] and [3, 10] to the
plot function.
Example Draw a line in a diagram from position (1, 3) to
position (8, 10):
plt.plot(xpoints, ypoints)
plt.show()
Matplotlib Line
Linestyle
You can use the keyword argument linestyle, or shorter ls, to change the style of the plotted line :
You can use the keyword argument color or the shorter c to set the color of the line:
You can plot as many lines as you like by simply adding more plt.plot() functions:
Example
Draw two lines by specifying a plt.plot() function for each line:
y1 = np.array([3, 8, 1, 10])
y2 = np.array([6, 2, 7, 11])
plt.plot(y1)
plt.plot(y2)
plt.show()
Creating Bars
With Pyplot, you can use the bar() function to draw bar graphs:
plt.bar(x,y)
plt.show()
Horizontal Bars
If you want the bars to be displayed horizontally instead of vertically, use the barh() function:
Example
Draw 4 horizontal bars:
plt.barh(x, y)
plt.show()
Bar Color
The bar() and barh() take the keyword argument color to set the color of the bars:
Example
Draw 4 red bars:
Example
A simple pie chart:
plt.pie(y)
plt.show()
Labels
Add labels to the pie chart with the labels parameter.
The labels parameter must be an array with one label for each wedge:
Example
A simple pie chart:
As mentioned the default start angle is at the x-axis, but you can change the start angle by
specifying a startangle parameter.
The startangle parameter is defined with an angle in degrees, default angle is 0:
Example
Start the first wedge at 90 degrees:
Example
Specify a new color for each wedge: