0% found this document useful (0 votes)
42 views44 pages

Chapter 5

The document provides a comprehensive overview of creating classes and objects in Python, detailing the syntax for class and object creation, the use of the 'self' parameter, and the importance of constructors. It includes examples of default and parameterized constructors, as well as methods for adding, modifying, and deleting attributes. Additionally, it highlights that Python does not support constructor overloading, contrasting it with other OOP languages.

Uploaded by

pjanhavi055
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)
42 views44 pages

Chapter 5

The document provides a comprehensive overview of creating classes and objects in Python, detailing the syntax for class and object creation, the use of the 'self' parameter, and the importance of constructors. It includes examples of default and parameterized constructors, as well as methods for adding, modifying, and deleting attributes. Additionally, it highlights that Python does not support constructor overloading, contrasting it with other OOP languages.

Uploaded by

pjanhavi055
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/ 44

5.

1 Creating Classes and Objects


Class creates a user-defined data structure, which holds its own data members and member
functions, which can be accessed and used by creating an instance of that class. A class is like a
blueprint for an object.

5.1.1 Creating class:


To create class, keyword ‘class’ followed by class_name and colon (:). The data members and member –
functions are defined under this signature with indent.
Example:

class Test1:
def sayHello(self):
print(“Hello from class Test1”)
def sayHi(self)
print(“Hi from class Test1”)

Note the indents given in above example.


Two member-functions sayHello() and sayHi( ) are defined within indent of class Test1.
And the statements of both member functions are written within indent of specific member function.
Now we will add data members to class.

class Test2:
x=5
y=10
def sayHello(self):
print("Hello from class Test")
def sayHi(self):
print("Hi from class Test")

Again note the indents for data-members and member-functions. The data must be initialized.
(Because Python don't allow explicit declaration of data-members)
And the scope of data-members upto that class.
Unlike other languages, to use data-members in member-function we must take help of parameter '
self ’ which is almost like 'this pointer ' of C++ and 'this' of Java.)

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


Consider another class where data-members are accessed by using parameter 'self ' .

class Test3:
x=5
def accept_x(self):
print("Enter value for x")
self. x = int(input())
def show_x(self):
print("x =",self.x)
def reset_x(self):
self.x =5

Line-2 declares data-member 'x' and it was accessed in line-5, line-7 and line-9 by using parameter
'self’ in three different member-functions. We can call these member functions in required order by
using object from anywhere.

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


5.1.2 Declaring Object
An object is an instance of a class. We can also say that, an object allocates memory to data-members
(attributes) of class and member-functions perform desired operations on the attributes of invoking
objects. Following is the syntax to create an object of class.

object_name = class_ name ( )

For example, to declare object of above class Test3, then it will be as follows.

t= Test3()

Don't forget the parenthesis ( ) with class name Test3. If parenthesis is not applied, then it won't be
object, but instead it will be a reference. And a reference will not be helpful to call/use/access
members of class Test3.
After declaring object, we can work with data-members and member-functions by using object name
and dot operator (.). Refer following complete example.

class Test2:
x=5
y=10
def sayHello(self):
print("Hello from class Test")
def sayHi(self):
print("Hi from class Test")
t=Test2()
print("x=", t.x)
print("y=", t.y)
t.sayHello();
t.sayHi();

Output:
x= 5
y= 10
Hello from class Test
Hi from class Test

In similar way, we can declare any number of objects of a class and works on its members. Example:
t1=Test2()
t2=Test2()
t3=Test2()
OR
t1, t2, t3 = Test2( ), Test2( ), Test2( )

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


5.1.3 The 'Self' Parameter
Every member-function of a class must have ‘self' parameter.
The parameter self is a reference to the current/invoking object, and is used to access attributes and
member-functions that belongs to the class. It does not have to be named self only, you can name it
whatever you like, but it has to be the first parameter of any function in the class.
To work with any data-member of that class within the member-function, parameter self is
mandatory.
Refer following example, where attribute x is accessed by using parameter self only.

class Test3:
x=5
def accept_x(self):
print("Enter value for x")
self.x=int(input())
def show_x(self):
print("x = ",self.x)
def reset_x(self):
self.x =5
print("x = ",self.x)
t1=Test3()
t1.accept_x()
t1.show_x()
t1.reset_x();
If we did not use parameter self in above example, then ' x' would have either shown declaration error:
“x is undeclared".

a) Example that combines use of parameter self and multiple object declarations:

class Student:
roll = 0
name = ""
wt = 0.0
def accept(self):
print("Enter roll number")
self.roll = int(input( ))
print("Enter name")
self.name=input( )
print("Enter weight")
self.wt=float(input( ))
def display(self):
print("Roll number :",self.roll)
print("Name :",self.name)
print("Weight :",self.wt)
Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi
s1 = Student( ) # declaring object 's1' of class Student
s2 = Student( ) # declaring object 's2' of class Student
print("Accepting Details of first student")
s1.accept( ) # calling to member-function accept_details( ) for object 's1'
print("Accepting Details of second student")
s2.accept( ) # calling to member-function acceptdetails( ) for object 's2'
print("Showing Details of first student")
s1.display( ) # calling to member-function show_details( ) for object ‘s1’
print("Showing Details of second student")
s2.display( ) # calling to member-function show details( ) for object 's2'

Output
Accepting Details of first student
Enter roll number
10
Enter name
Akshay
Enter weight
80
Accepting Details of second student
Enter roll number
20
Enter name
Amol
Enter weight
75
Showing Details of first student
Roll number : 10
Name : Akshay
Weight : 80.0
Showing Details of second student
Roll number : 20
Name : Amol
Weight : 75.0

Note that, three attributes roll, name and wt needed to be initialized for their declaration to be happen.
Also note that, the member-functions are using parameter self to refer to attributes.
One more thing, we don't have to pass any actual parameter to member-functions for parameter self.
The parameter self will get initialized by invoking object itself.

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


b) Example that show parameter self with additional parameters

class Student:
def accept(self,x,y,z): # Function with additional three parameters
self.roll = x
self.name = y
self.wt = z
def display(self):
print("Roll number :",self.roll)
print("Name :",self.name)
print("Weight :",self.wt)
s1 = Student( )
s2 = Student( )
print("Accepting Details of first student")
s1.accept(15, "Akshay" , 80)
print("Accepting Details of second student")
s2.accept(20,"Amol", 75 )
print("Showing Details of first student")
s1.display( )
print("Showing Details of second student")
s2.display( )

Output:
Accepting Details of first student
Accepting Details of second student
Showing Details of first student
Roll number : 15
Name : Akshay
Weight : 80
Showing Details of second student
Roll number : 20
Name : Amol
Weight : 75

This program is to clear that, we have not passed any parameter for ‘self’, but we needed to pass for
other three parameters.

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


5.1.4 Creating Instant Attributes of object OR Externally modifying
Object’s Properties

In class student of Example b, we saw that the data members must be initialized to let their declaration
happen.

class Student:
roll = 0
name = ""
wt = 0.0

But it’s a tedious and code extending job. So we can also declare/add new data members from a
member function using ‘self’ as below.

class Student:
def accept(self):
print("Enter roll number")
self.roll = int(input( ))
print("Enter name")
self.name=input( )
print("Enter weight")
self.wt=float(input( ))
def display(self):
print("Roll number :",self.roll)
print("Name :",self.name)
print("Weight :",self.wt)
s1 = Student( )
s2 = Student( )
s1.accept( )
s2.accept( )
s1.display( )
s2.display( )

Here we can see that declaration of all three members i,e, roll, name and wt is done. Means whenever
function accept() is called for any object, the parameter self will automatically create and add three
data members for invoking object.

s1 and s2 are two objects of class student that add and initializes attributes name roll and wt to class
student. Similarly, we can add new attributes from any member-functions. The only condition is, these
attributes will be added only when that member-function is called (if not called, then these attributes
will not be added.)

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


Another thing is, consider we have declared two objects of above class students; object s1 and object
s2. Now, if we called the accept( ) function only for object s1, not for object s2. Then attributes name
roll and wt will be added only to object s1, not to object s2.

Another way for externally adding attributes to an object is, by using directly object name with
attribute's initialization. Refer following code.

class Test:
def sayHello(self):
print("Hello all")
t1=Test()
t2=Test()
t1.x= 10 #externally added attribute in object t1
print(t1.x)
print(t2.x) # but not available for object t2 of same class

Note that, attribute `x' is externally added for object t1 and initialized with 10. But this type of external
insertion of attribute will be available only to that particular object. Therefore if we print the attribute
'x ' for object t2 (at Line-8) then it will show following error :

AttributeError: ‘Test' object has no attribute 'x'

This clearly means that, if we declare attributes within class (internally), then those attributes are
available to every declared object of that class. But if we add attributes externally, then those attributes
are available to that particular object only.

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


5.1.5 Deleting an Attribute
We can also delete an attribute by using keyword 'del’. For example,
class Test:
x=5
y=10
def show_val(self):
print("x=",self.x)
print("y=",self.y)
t1=Test( )
t2=Test( )
t1.show_val( )
t2.show_val()
del Test.x # Delete attribute x from class Test
print("t1.x =",t1.x)
print("t2.x =",t2.x )

Note that, in Line-11 we externally delete attribute 'x from class Test. Hence, above code will show
error AttributeError 'Test' object has no attribute "x' in Line-12 and Line-13.

5.1.6 Defining Constructor OR The __init__( ) Method


Constructors are generally used for instantiating an object.
• The task of constructors is to initialize(assign values) to the data members of the class when an object
of class is created.
• In Python the __init__() method is called the constructor and is always invoked automatically when an
object is created.

Syntax of constructor declaration :


def __init__(self):
# body of the constructor

class Student:
def __init__(self):
print("Constructor of class Student")
print("Declaring first object")
s1 = Student( ) # will create object sl and constructor executes here
print("Declaring second object")
s2 = Student( ) # will create object s2 and constructor executes here

Two objects s1 and s2 are declared for class Student and hence, constructor __int__ () function executes
individually for both object objects. Hence, note that output of above code.

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


Declaring first object
Constructor of class Student
Declaring second object
Constructor of class Student

Characteristics of constructor

 must be named as __init__ only.


 will be executed automatically when object is declared.
 can be called manually. (whenever required to reset object's attribute’s values.
We can also declare and initialized attributes in constructor.
Types of Constructors

 Default constructor
 Parameterized constructor

5.1.6.1 Default Constructor

The default constructor is simple constructor which does not accept any arguments. Its definition has only one
argument which is a reference to the instance being constructed.
Example:

class Student :
def __init__(self): # this is default constructor to initialize default values to attributes
self.age = 18
self.gender = "Male"
self.dept = "CS"

def show_values(self):
print("Age :",self.age)
print("Gender :",self.gender)
print("Department :",self.dept)

s1 = Student( ) # will create object ‘s1' and invoke default constructor


s2 = Student( ) # will create object ‘s2' and invoke default constructor
print("Default values of first student")
s1.show_values( )
print("Default values of second student")
s2.show_values( )

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


5.1.6.2 Parameterized Constructor
Constructor with parameters is known as parameterized constructor.
It is used to initialize/assign different values to attributes of different objects.
The parameterized constructor take its first argument as a reference to the instance being constructed
known as self and the rest of the arguments are provided by the programmer.
Example:
class Student :
def __init__(self,a,g,d): # this is default constructor to initialize default values to attributes
self.age = a
self.gender = g
self.dept = d
def show_values(self):
print("Age :",self.age)
print(" Gender :",self.gender)
print("Department :",self.dept)
s1 = Student(30, "Akshay", "Male" ) # will create object ‘s1' and invoke default constructor
s2 = Student(37, "Amol", "Male" ) # will create object ‘s2' and invoke default constructor
print("Default values of first student")
s1.show_values( )
print("Default values of second student")
s2.show_values( )

Q] Define a class rectangle using length and width.It has a method which can compute area.
class rectangle:
def __init__(self,L,W):
self.L=L
self.W=W
def area(self):
return self.L*self.W
r=rectangle(2,10)
print(r.area())

Q] Create a circle class and initialize it with radius. Make two methods getarea and
getcircumference inside this class
class circle:
def __init__(self,radius):
self.radius=radius
def getarea(self):
return 3.14*self.radius*self.radius
def getcircumference(self):
return 2*3.14*self.radius
c=circle(5)
print("Area=",c.getarea())
print("Circumference=",c.getcircumference())

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


5.1.6.3 Constructor Overloading is not allowed in Python

Other OOP languages allow Constructor Overloading and Function Overloading to improve readability
of code. Python does not allow Constructor Overloading and Function Overloading.
Example:

class Student :
def __init__(self): # this is default constructor to initialize default values to attributes
self.age = 18
self.gender = "Male"
self.dept = "CS"
def __init__(self,a,g,d): # defines parameterized constructor
self.age = a
self.gender = g
self.dept = d
def show_values(self):
print("Age :",self.age)
print(" Gender :",self.gender)
print("Department :",self.dept)
s1 = Student( ) # will create object s1 and invokes default constructor
s1 .show_values( )
s2 = Student( 18,"Female","CO") # will create object s2 and invokes parameterized constructor
s2.show_values( )

Above code will show error, Python strictly don't allow function overloading or constructor
overloading
It is because; in Python even a function is also treated as object. Hence, always last defined body of
overloaded constructor and function will be considered for use.
Hence, for above class Student, the last defined constructor (parameterized with 'a','g' and ‘d’ ) will get
considered to use.
Hence, it will show error if we use first constructor (default constructor).

Traceback (most recent call last):


File "C:/Python/Python38/PRACTICALS/Chapter 5/9_overloading.py", line 14, in <module>
s1 = Student( ) # will create object s1 and invokes default constructor
TypeError: __init__() missing 3 required positional arguments: 'a', 'g', and 'd'

But if we comment lines s1 = Student( ) and s1 .show_values( ) , then it will invoke parameterized
construction which will give correct output.

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


5.1.6.4 Constructor with Default Arguments

- As the Python don't allow constructor overloading and function overloading. But by assigning default
values to constructor's parameters we can achieve similar benefits as we can do by overloading. Here
is an example of combining application of initialization through default constructor and parameterized
constructor.

class Student :
def __init__(self,a=18,g="Male",d="CO"): # defines parameterized constructor with default values
self.age = a
self.gender = g
self.dept = d
def show_values(self):
print("Age :",self.age)
print(" Gender :",self.gender)
print("Department :",self.dept)
s1 = Student( ) # will create object s1 and invokes constructor with default values
print("Initialized Values of First Object")
s1 .show_values( )
s2 = Student( 20,"Female","IT") # will create object s2 and invokes parameterized constructor with
default values
print("Initialized Values of Second Object")
s2.show_values( )
Output:
Initialized Values of First Object
Age : 18
Gender : Male
Department : CO
Initialized Values of Second Object
Age : 20
Gender : Female
Department : IT

Note that, the parameterized constructor with default values will make it optional to pass arguments
for object s1.
And when arguments are passed for object s2, it will get updated.

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


5.1.7 Defining destructor OR The __del __ () Method

A class can define a special method called destructor with the help of _ _del_ _().
It is invoked automatically when the scope of an object expires or the instance (object) is about to
be destroyed.
It is mostly used to clean up non memory resources used by an instance(object).

Example :

class Test:
def __init__(self):
print("Constructor is Invoked")
def __del__(self):
print("Destructor is Invoked")
s1=Test( )
del s1
s2 = Test()
del s2

Output:

Constructor is Invoked
Destructor is Invoked
Constructor is Invoked
Destructor is Invoked

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


5.1.8 "Can Manually Call Constructor and Destructor..?"
In other object oriented languages, execution of constructor and destructor is automatic i.e, they will
execute at their fixed moments, But Python allows to call constructor and destructor manually, if
required.
They will execute at their fixed moments but additionally they will execute on our manual call also.

class Test:
def __init__(self):
print("This is constructor")
def __del__(self):
print("This is destructor")
print("Declaring object t1")
t1=Test( ) #will create object t1 and invokes constructor automatically
t1.__init__() #calling constructor manually
t1.__del__() # calling destructor manually
print("Last Line") #scope of t1 expires and invokes destructor automatically

Output:
Declaring object t1
This is constructor
This is constructor
This is destructor
Last Line

Here,
Line- 7 declares object t1 and hence, constructor executes for object t1, automatically (according to its
characteristics).
Line-8 manually calls to constructor for object
Line-9 manually calls to destructor for object
Line-10 is last line of main script and after executing print statement, scope of t1 expires. Hence,
destructor executes automatically.

- It is possible that while working on an object, we need to reset the initial values of an object that we
initialized through default constructor; in other languages we cannot do it hence we are forced to
declare and use a new object, But Python allows to call constructor manually. Hence, if required to
reset then we manually call to constructor and reset the initialized values for an object.
- Same thing for destructor! Generally we define destructor to release the resources occupied by an
object. It is possible that we want to release the resources of occupied by an object even earlier to
expiration of its scope and earlier to its automatic execution. So we should call a destructor manually.
Although for any object, its constructor and destructor is called then also its constructor and destructor
will definitely execute on its automatic moments also.

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


5.1.9 Deleting an Object

Python allows to manually delete entire object by using keyword 'del ' followed by the object to be
deleted. For example,

class Student:
………..
……..
s1 = Student( )
s2 = Student( )

del s1 # deletes object ‘s2'


del s2 # deletes object ‘s1'

-Once an object is manually deleted, that object or its instances will no more be available to use. Refer
following code and error.

class Student:
x1=10
s1=Student()
print(“s1.x=”, s1.x)
del s1 # deletes object ‘s1'
print(“s1.x=”, s1.x) # will show NameError

5.1.10 The Pass Statement


We know that, Python's class or functions don't have pair of curly braces ({}) to specify area. Instead, it
has indents. A class or function definitions cannot be empty, but for some reason if we required to
define a class or function definition with no content, put in the pass statement to avoid getting an error.
For example,
class A:
pass
class B:
def method1 (self):
pass
def method2(self):
print("This is method2")
b = B()

b.method1()
b.method2()

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


- For the same purpose, we can also use keyword None.
class A:
pass
class B:
def method1 (self):
None
def method2(self):
print("This is method2")
b = B()

b.method1()
b.method2()

5.2 Data Hiding


- Data hiding is one of the important features of Object Oriented Programming which allows preventing
the attributes and functions of a program to access directly the internal representation of a class type.
By default every members of a class can be accessed outside the class. We can prevent this by making
class members private or protected.
- In Python, we use double underscore ( _ _ ) before the attributes name to make those attributes
private. We can use single underscore ( _ ) before the attributes name to make those attributes
protected.

class Test:
__a =15 # declares private variable
_b =20 # declares protected variable
t1=Test()
print("Private Variable=", t1.__a)
print("Protected Variable=", t1._b)

Here
line 1 declares private variable
line 2 declares protected variable
line 5 prints value of private variable outside class(will show error)
line 6 prints value of protected variable outside class
In the above program, we tried to access private attribute outside the class using object and it threw7a-
an exception,
Traceback (most recent call last):
File "C:/Python/Python38/PRACTICALS/Chapter 5/13_Data Hiding.py", line 5, in <module>
print("Private Variable=", t1.__a)
AttributeError: 'Test' object has no attribute '__a'
We can access the value of hidden attribute by a tricky syntax as

object._className__attrNmae

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


Let us re-write above program with above change in Line-5.

class Test:
__a =15 # declares private variable
_b =20 # declares protected variable
t1=Test()
print("Private Variable=", t1._Test__a)
print("Protected Variable=", t1._b)

Output:
Private Variable= 15
Protected Variable= 20

- From above output, note that the protected variable will be available outside the class for sure.
- However, these concepts of Data-Hiding are valid only while accessing members outside the class. But
there is no effect of Data-Hiding within the class. Here is another program, which increments values of
private and protected attributes within the class.

class Test:
__a = 10
_b =20
def increment(self):
print("Initial values")
print("Private variable =", self.__a )
print("Protected variable = ",self._b)
print(" \nAfter incrementing")
self.__a+=1
self._b+=1
print("Private variable =", self.__a)
print("Protected variable = ",self._b)
t1=Test()
t1.increment()

Output:
Initial values
Private variable = 10
Protected variable = 20

After incrementing
Private variable = 11
Protected variable = 21

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


5.3 Inheritance and Composition
Classes in object oriented languages would be deficient if it does not support inheritance, Inheritance is
a powerful feature of object oriented language. Inheritance means deriving properties of one class into
another class.

- The class whose properties are being derived is called as base class or parent class or super class.
And the class which derives properties of base class is called as derived class or child class or sub class.

Benefits of Inheritance:

 It represents real-world relationships in easy manner.


 It provides reusability of a code. We don t have to write the same code again. Also, it allows us to
add, or update more features to a class without modifying it.
 It is transitive in nature, which means that if class B inherits from another class A, then all the
subclasses of B would automatically inherit from class A.

In Python, to inherit a class we have following syntax.

class BaseClass:
………….
………….
class DerivedClass(BaseClass):

……….
………

The base class name is provided inside parenthesis followed by derived class name. Python supports
five types of inheritance

 Single Inheritance
 Multiple Inheritance
 Multilevel Inheritance
 Hierarchical Inheritance
 Hybrid Inheritance

Let us discuss these all and other additional required concepts in inheritance.

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


A] Single Inheritance
When a class is derived from only one base class, it is called Single Inheritance.

Example 1:

class Student:
def accept(self):
print("Enter Name and Roll")
self.name=input()
self.roll=int(input())
def display(self):
print("Name is", self.name)
print("Roll is", self.roll)
class Marks(Student):
def accept_marks(self):
print("Enter Marks")
self.m=int(input())
def display_marks(self):
print("Marks are",self.m)
m1=Marks()
m1.accept()
m1.accept_marks()
m1.display()
m1.display_marks()

Output:

Enter Name and Roll


akshay
15
Enter Marks
45
Name is akshay
Roll is 15
Marks are 45

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


Example 2:

class Student:
def accept(self):
self.name='Amol'
self.roll= 15
def display(self):
print("Name is", self.name)
print("Roll is", self.roll)
class Marks(Student):
def accept_marks(self):
self.m1=50
self.m2=65
def display_marks(self):
print("Marks of Subject 1 are",self.m1)
print("Marks of Subject 2 are",self.m2)
M=Marks()
M.accept()
M.accept_marks()
M.display()
M.display_marks()

Output:

Name is Amol
Roll is 15
Marks of Subject 1 are 50
Marks of Subject 2 are 65

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


 Constructor and Destructor in Inheritance

Consider following example of constructor and destructor in Inheritance.

class Student:
def __init__(self):
print("Constructor of Base class")
def __del__(self):
print("Destructor of Base class")
class Marks(Student):
def __init__(self):
print("Constructor of Derived class")
def __del__(self):
print("Destructor of Derived class")

M=Marks()
del M
print("Main Area Ends")

In above example we have created constructor __init__() and destructor __del__ in both base and
derived classes.
Python interpreter will treat this as method overriding (because of same names in base and derived
class).
Hence constructor and destructor of derived class only executed.

Output:
Constructor of Derived class
Destructor of Derived class
Main Area Ends

No constructor and destructor of base class executed.

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


 Calling Base Class Constructor and Destructor from Derived class

If we want to call Base Class Constructor and Destructor from Derived class by using:

base_class_name.__init__(self)
and
base_class_name.__del__(self)

Example

class Student:
def __init__(self):
print("Constructor of Base class")
def __del__(self):
print("Destructor of Base class")
class Marks(Student):
def __init__(self):
Student.__init__(self)
print("Constructor of Derived class")
def __del__(self):
Student.__del__(self)
print("Destructor of Derived class")
M=Marks()
del M
print("Main Area Ends")

Output:
Constructor of Base class
Constructor of Derived class
Destructor of Base class
Destructor of Derived class
Main Area Ends

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


 Passing parameters to Base Class Constructor from Derived Class Constructor

class Student:
def __init__(self, name, roll):
self.name= name
self.roll= roll
def display(self):
print("Name is", self.name)
print("Roll is", self.roll)
class Marks(Student):
def __init__(self,name,roll,m1,m2):
Student.__init__(self, name, roll)
self.m1=m1
self.m2=m2
def display_marks(self):
print("Marks of Subject 1 are",self.m1)
print("Marks of Subject 2 are",self.m2)
M=Marks("akshay",25,57,65)
M.display()
M.display_marks()

Output:
Name is akshay
Roll is 25
Marks of Subject 1 are 57
Marks of Subject 2 are 65

In above example, name and roll is passed as argument to constructor in Base class Student from
constructor in Derived class Marks.

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


B] Multiple Inheritances
When a class is derived from more than one base class it is called multiple Inheritance. The derived
class inherits all the features of the base case.

Syntax:
Class Base1:
Body of the class
Class Base2:
Body of the class
Class Derived(Base1, Base2):
Body of the class

Example
class A:
attr1=10
def method1(self):
print("Hello Method of Class A")
class B:
attr2=20
def method2(self):
print("Hello Method of Class B")
class C(A, B):
attr3=30
def method3(self):
print("Hello Method of Class C")
obj = C()
obj.method1()
obj.method2()
obj.method3()
print(obj.attr1)
print(obj.attr2)
print(obj.attr3)

Output:-
Hello Method of Class A
Hello Method of Class B
Hello Method of Class C
10
20
30

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


Example 2:-
class Student:
def accept(self):
print("Enter Name and Roll")
self.name=input()
self.roll=int(input())
def display(self):
print("Name is", self.name)
print("Roll is", self.roll)
class Marks:
def accept_marks(self):
print("Enter Marks")
self.m1=int(input())
self.m2=int(input())
def display_marks(self):
print("Marks of Subject 1 are",self.m1)
print("Marks of Subject 2 are",self.m2)
class Result(Student, Marks):
def accept_extra(self):
print("Enter Exatra Marks")
self.m3=int(input())
def calculate(self):
print("Exatra Marks are",self.m3)
self.total=self.m1+self.m2+self.m3
print("Total Marks are",self.total)
R1=Result()
R1.accept()
R1.accept_marks()
R1.accept_extra()
R1.display()
R1.display_marks()
R1.calculate()
Output:
Enter Name and Roll
Akshay
24
Enter Marks
67
54
Enter Exatra Marks
20
Name is Akshay
Roll is 24
Marks of Subject 1 are 67
Marks of Subject 2 are 54
Exatra Marks are 20
Total Marks are 141

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


 Passing parameters to Base Class Constructor from Derived Class Constructor in Multiple
Inheritance
class A:
def __init__(self,a):
self.a=a
print("Value of a in Class A is ",self.a)
class B:
def __init__(self,b):
self.b=b
print("Value of b in Class B is ",self.b)
class C(A, B):
def __init__(self,a,b,c):
A.__init__(self,a)
B.__init__(self,b)
self.c=c
print("Value of c in Class C is ",self.c)
obj = C(10,20,30)

Output:-
Value of a in Class A is 10
Value of b in Class B is 20
Value of c in Class C is 30

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


Example 2:

class Student:
def __init__(self, name, roll):
self.name= name
self.roll= roll
def display(self):
print("Name is", self.name)
print("Roll is", self.roll)
class Marks:
def __init__(self,m1,m2):
self.m1=m1
self.m2=m2
def display_marks(self):
print("Marks of Subject 1 are",self.m1)
print("Marks of Subject 2 are",self.m2)
class Result(Student, Marks):
def __init__(self,name, roll, m1, m2, m3):
Student.__init__(self,name,roll)
Marks.__init__(self,m1,m2)
self.m3=m3
def calculate(self):
print("Extra Marks are",self.m3)
self.total=self.m1+self.m2+self.m3
print("Total Marks are",self.total)
R=Result("Akshay",23,56,67,20)
R.display()
R.display_marks()
R.calculate()

Output
Name is Akshay
Roll is 23
Marks of Subject 1 are 56
Marks of Subject 2 are 67
Extra Marks are 20
Total Marks are 143

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


C] Multilevel Inheritance
When a class is deived from already derived class, it is called as Multilevel Inheritance.
Syntax:
class A
-------------
class B(A)
------------
class C(B)
------------
Example:
class A:
attr1=10
def method1(self):
print("Hello Method of Class A")
class B(A):
attr2=20
def method2(self):
print("Hello Method of Class B")
class C(B):
attr3=30
def method3(self):
print("Hello Method of Class C")
obj = C()
obj.method1()
obj.method2()
obj.method3()
print(obj.attr1)
print(obj.attr2)
print(obj.attr3)

Output:-
Hello Method of Class A
Hello Method of Class B
Hello Method of Class C
10
20
30

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


Example:
class Student:
def accept(self):
print("Enter Name and Roll")
self.name=input()
self.roll=int(input())
def display(self):
print("Name is", self.name)
print("Roll is", self.roll)
class Marks(Student):
def accept_marks(self):
print("Enter Marks")
self.m1=int(input())
self.m2=int(input())
def display_marks(self):
print("Marks of Subject 1 are",self.m1)
print("Marks of Subject 2 are",self.m2)
class Result(Marks):
def accept_extra(self): Output:
print("Enter Exatra Marks") Enter Name and Roll
self.m3=int(input()) Akshay
def calculate(self): 23
print("Extra Marks are",self.m3) Enter Marks
self.total=self.m1+self.m2+self.m3 50
print("Total Marks are",self.total) 60
Enter Exatra Marks
R1=Result() 30
R1.accept() Name is Akshay
R1.accept_marks() Roll is 23
R1.accept_extra() Marks of Subject 1 are 50
R1.display() Marks of Subject 2 are 60
R1.display_marks() Extra Marks are 30
R1.calculate() Total Marks are 140

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


5.4 Abstract Classes in Python
A class which contains one or more abstract methods is called an abstract class. An abstract method is
a method that has a declaration but does not have an implementation.
An abstract class can be considered as a blueprint for other classes.
We can not create objects of Abstract Class directly.

Why use Abstract Base Classes :


It allows you to create a set of methods that must be implemented within any child classes built from
the abstract class.
While we are designing large functional units we use an abstract class.
By defining an abstract base class, you can define a common Application Program Interface(API) for
a set of subclasses. It is useful in situations where a third-party is going to provide implementations,
such as with plugins.

How Abstract Base classes work :


By default, Python does not provide abstract classes.
Python comes with a module which provides the base for defining Abstract Base classes(ABC) and that
module name is abc.
ABC works by decorating methods of the base class as abstract and then registering concrete classes as
implementations of the abstract base.
A method becomes abstract when decorated with the keyword @abstractmethod. For

Syntax to create an abstract class in Python:


from abc import ABC
class <Abstract_Class_Name>(ABC):
# body of the class

Here we just need to inherit the ABC class from the abc module in Python.

Example of abstract classes:


from abc import ABC
class DemoAbstractClass(ABC):
pass

To define an abstract method we use the @abstractmethod decorator of the abc module.
It tells Python that the declared method is abstract and should be overridden in the child classes.
Syntax to create an abstract method in Python:
from abc import ABC, abstractmethod
class <Abstract_Class_Name>(ABC):
@abstractmethod
def <abstract_method_name>(self,other_parameters):
pass

We just need to put this decorator over any function we want to make abstract, and the abc module
takes care of the rest.

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


Example to demonstrate abstract classes:
from abc import ABC, abstractmethod
class DemoAbstractClass(ABC):
@abstractmethod
def abstract_method_name(self):
pass

Example 1:
from abc import ABC, abstractmethod
class Polygon(ABC):
def display(self):
print("Display is Concrete Method")
@abstractmethod
def noofsides(self): # abstract method
pass
class Triangle(Polygon):
def noofsides(self): # overriding abstract method
print("Triangle has 3 sides")
class Quadrilateral(Polygon):
def noofsides(self): # overriding abstract method
print("Quadrilateral has 4 sides")
class Pentagon(Polygon):
def noofsides(self): # overriding abstract method
print("Pentagon has 5 sides")
class Hexagon(Polygon):
def noofsides(self): # overriding abstract method
print("Hexagon has 6 sides")

R = Triangle()
R.noofsides()
R.display()

K = Quadrilateral()
K.noofsides()
K.display()

P = Pentagon()
P.noofsides()
P.display()

H = Hexagon()
H.noofsides()
H.display()

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


Output:

Triangle has 3 sides


Display is Concrete Method
Quadrilateral has 4 sides
Display is Concrete Method
Pentagon has 5 sides
Display is Concrete Method
Hexagon has 6 sides
Display is Concrete Method

Example 2:
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def move(self):
pass
class Human(Animal):
def move(self):
print("I can walk and run")
class Snake(Animal):
def move(self):
print("I can crawl")
class Dog(Animal):
def move(self):
print("I can bark")
class Lion(Animal):
def move(self):
print("I can roar")

R = Human()
R.move()
K = Snake()
K.move()
R = Dog()
R.move()
K = Lion()
K.move()
Output:
I can walk and run
I can crawl
I can bark
I can roar

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


5.5 Method Overloading
Python does not supports method overloading. We may overload the methods but can only use the
latest defined method.

class Test:
def product(self,a, b): # First product method Takes two argument and print their product
self.p = self.a * self.b
print("Product of two numbers is ", self.p)
def product(self,a, b, c): # Second product method Takes three argument and print their product
self.a=a
self.b=b
self.c=c
self.p = self.a * self.b* self.c
print("Product is ", self.p)
t= Test()
t.product(4, 5) # This line shows an error
t.product(4, 5, 5) # This line will call the second product method

In the above code we have defined two product method, but we can only use the second product
method, as python does not supports method overloading. We may define many method of same name
and different argument but we can only use the latest defined method. Calling the other method will
produce an error. Like here calling product(4, 5) will produce an error as the latest defined product
method takes three arguments.
If we are in strictly need of such implementation, then we can use function with default arguments.
Example:
class Test:
def product(self,a=1,b=1,c=1):
self.a=a
self.b=b
self.c=c
self.p = self.a * self.b* self.c
print("Product is ", self.p)
t= Test()
print("Product of two numbers is")
t.product(4, 5)
print("Product of three numbers is")
t.product(4, 5, 5)

Output:
Product of two numbers is
Product is 20
Product of three numbers is
Product is 100s

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


5.6 Method Overriding
Method overriding needs support of inheritance. Method overriding means redefining method of base
class into derived class.
Or we can say, overriding is the property of derived class to change the implementation of a by one of
its base class.
When a method in a subclass has the same name, same parameters or signature and same return
type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the
method in the super-class.
In method overriding, the new re-defined method of derived class hides the accessibility of on method
of base. Thus the object of derived class will by default gets the access of new method of derived class
only.
Example:

class A:
def sayHello(self):
print("Hello from class A")
class B(A):
def sayHello(self):
print("Hello from class B")
b=B()
b.sayHello()

Output:
Hello from class B
In above example method sayHello() from class A will not be invoked as method sayHello() from class
B hides it.

 Use of Super to Access Members of Base Class


Like other object oriented languages, Python also provides keyword super to make point towards
member of Base class. Here is the modification of above example to call to sayHello( ) function.
The super() method helps us in overriding methods in new style classes. Its syntax is as follows:

super(derived_class_name,self).overridden_method_name()

Example:
class A:
def sayHello(self):
print("Hello from class A")
class B(A):
def sayHello(self):
super(B,self).sayHello()
print("Hello from class B")
b=B()
b.sayHello()
Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi
Output:
Hello from class A
Hello from class B

We can also overcome the problem of Method overriding by following way:

class A:
def sayHello(self):
print("Hello from class A")
class B(A):
def sayHello(self):
A.sayHello(self) # calling method in Base class from method in derived class
print("Hello from class B")
b=B()
b.sayHello()

Output:
Hello from class A
Hello from class B

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


5.6 Customization via Inheritance Specializing Inherited
Methods
1. _ _str_ _()

The python __str__ method returns the object representation in a string format. This method is
supposed to return a human-readable format which is used to display some information about the
object. This method is called when an object is printed or manually _ _str_ _ ( ) function is called for an
object.
The programmer has to define (actually override) this function and this method must return the String,
If we don't implement _ _str_ _( ) function in a class, then built-in object implementation is used that
actually calls _ _repr _ _ () function.
Example.
class A:
pass
class B:
def __str__(self):
return "Hello from object of class B"
a1=A()
b1=B()
print(a1) #__str__() is not defined for object a1 so repr is called
print(b1) #__str__( ) is defined for object bl

#print(b1.__str__())
Note the class A does not defines __str__( ) function but class B does. We will get following output for
this.

Output:
<__main__.A object at 0x000002AB419FCDF0>
Hello from object of class B

You may get some other hashcode for object a1 in your system, but object b1 is definitely executing _
__str__() function defined in class B.

2. _ _repr_ _()

The function is used as a fallback/backup that executes for an object on the same moments but only
when _ _str _ _( ) function is not defined for that object. But remember that, There is no fallback if
__repr__ ( ) function implementation is missing.
- Now the major difference between these two functions is, the _ _str_ _() function must return string
only whereas the _ _repr _ _() function can return any informatics objet such as Tuple or Dictionary or
List or anything. Here is an example.

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


Example:

class A:
pass
class B:
def __repr__(self):
return {1:"one", 2:"two"}
a1=A()
b1=B()
print("When object a1 gets ptinted : ",a1) #__str__() is not defined for object a1
print("When object b1 gets Printed :",b1.__repr__()) #__str__( ) is defined for object bl

Output:
When object a1 gets ptinted : <__main__.A object at 0x000001B6AC8ABDF0>
When object b1 gets Printed : {1: 'one', 2: 'two'}

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


NumPy
NumPy is a Python library used for working with arrays.
It also has functions for working in domain of linear algebra, fourier transform, and matrices.
NumPy stands for Numerical Python.

Why Use NumPy?


In Python we have lists that serve the purpose of arrays, but they are slow to process.
NumPy aims to provide an array object that is up to 50x faster than traditional Python lists.
The array object in NumPy is called ndarray, it provides a lot of supporting functions that make
working with ndarray very easy.
Arrays are very frequently used in data science, where speed and resources are very important.

Installation of NumPy
If you have Python and PIP already installed on a system, then installation of NumPy is very easy.
Goto path:-
C:\Users\Admin\AppData\Local\Programs\Python\Python311\Scripts

Press cmd
Enter pip install numpy

Once NumPy is installed, import it in your applications by adding the import keyword:
import numpy
Now NumPy is imported and ready to use.
NumPy is usually imported under the np alias.
import numpy as np
Now the NumPy package can be referred to as np instead of numpy.

Create a NumPy ndarray Object


NumPy is used to work with arrays. The array object in NumPy is called ndarray.
We can create a NumPy ndarray object by using the array() function.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
print(type(arr))
Output:-
[1 2 3 4 5]
<class 'numpy.ndarray'>
Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi
To create an ndarray, we can pass a list, tuple or any array-like object into the array() method, and it will
be converted into an ndarray:

Example
Use a tuple to create a NumPy array:

import numpy as np
arr = np.array((1, 2, 3, 4, 5))
print(arr)

Output:-
[1 2 3 4 5]

0-D Arrays
0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-D array.

Example
Create a 0-D array with value 42
import numpy as np
arr = np.array(42)
print(arr)

1-D Arrays
An array that has 0-D arrays as its elements is called uni-dimensional or 1-D array.

Example
Create a 1-D array containing the values 1,2,3,4,5:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)

2-D Arrays
An array that has 1-D arrays as its elements is called a 2-D array.
These are often used to represent matrix or 2nd order tensors.
Example
Create a 2-D array containing two arrays with the values 1,2,3 and 4,5,6:

import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


3-D arrays
An array that has 2-D arrays (matrices) as its elements is called 3-D array.
Example
Create a 3-D array with two 2-D arrays, both containing two arrays with the values 1,2,3 and 4,5,6:
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(arr)

Check Number of Dimensions?


NumPy Arrays provides the ndim attribute that returns an integer that tells us how many dimensions
the array have.
Example
import numpy as np
a = np.array(42)
b = np.array([1, 2, 3, 4, 5])
c = np.array([[1, 2, 3], [4, 5, 6]])
d = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])

print(a.ndim)
print(b.ndim)
print(c.ndim)
print(d.ndim)

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


Pandas
Pandas is a Python library used for working with data sets.
It has functions for analyzing, cleaning, exploring, and manipulating data.
The name "Pandas" has a reference to both "Panel Data", and "Python Data Analysis"

Why Use Pandas?


Pandas allows us to analyze big data and make conclusions based on statistical theories.
Pandas can clean messy data sets, and make them readable and relevant.
Relevant data is very important in data science.

Advantages
 Fast and efficient for manipulating and analyzing data.
 Data from different file objects can be loaded.
 Easy handling of missing data
 Size mutability: columns can be inserted and deleted from DataFrame and higher dimensional
objects
 Data set merging and joining.
 Flexible reshaping and pivoting of data sets
 Powerful group by functionality for performing split-combine operations on data sets.

The first step of working in pandas is to ensure whether it is installed in the Python folder or not. If
not then we need to install it in our system using pip command.

pip install pandas


After the pandas have been installed into the system, you need to import the library. This module is
generally imported as:

import pandas as pd
Here, pd is referred to as an alias to the Pandas.

Series:
Pandas Series is a one-dimensional labeled array capable of holding data of any type (integer,
string, float, python objects, etc.). Pandas Series is nothing but a column in a table.

Creating a Series
import pandas as pd
import numpy as np
# simple array
data = np.array(['A', 'r', 'r', 'o', 'w'])
ser = pd.Series(data)
print(ser)

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


Output:-
0 A
1 r
2 r
3 o
4 w
dtype: object

Labels
If nothing else is specified, the values are labeled with their index number. First value has index 0, second
value has index 1 etc.
This label can be used to access a specified value.

Example
Return the first value of the Series:
print(ser[0])

Create Labels
With the index argument, you can name your own labels.
Example
import pandas as pd
a = [1, 7, 2]
myvar = pd.Series(a, index = ["x", "y", "z"])
print(myvar)

Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular


data structure with labeled axes (rows and columns). A Data frame is a two-dimensional data
structure, i.e., data is aligned in a tabular fashion in rows and columns. Pandas DataFrame
consists of three principal components, the data, rows, and columns.

import pandas as pd
data =
{
"Experience": [20, 10, 5],
"Salary": [50000, 40000, 15000]
}
#load data into a DataFrame object:
df = pd.DataFrame(data)
print(df)

Locate Row
As you can see from the result above, the DataFrame is like a table with rows and columns.
Pandas use the loc attribute to return one or more specified row(s)

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi


Example
#refer to the row index:
print(df.loc[0])

Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi

You might also like