Monday, January 26, 2026

UNIT 5 :-PYTHON PROGRAMMING B. Sc. IT SEM 5


 

DR. AJAY KUMAR PATHAK

ASSISTANT PROFESSOR


READ  ALL THE NOTES CHAPTER WISE  OF PYTHON PROGRAMMING FOR B. SC IT SEM 5 F.Y.U.G.P. 

UNIT 5
SUBJECT:- MJ-9 :(Th) PYTHON PROGRAMMING 

LEARN NOTES FROM HERE
PREPARED BY DR. AJAY KUMAR PATHAK 
                                ©Copyrights 
        MJ-9 PYTHON PROGRAMMING

Copyright © by Dr. Ajay kumar pathak

B. Sc IT SEMESTER 5 NOTES BASED ON NEP

SUBJECT : MJ - 9 (Th): PYTHON PROGRAMMING

(To be selected by the students from)

NOTES OF UNIT 5 OF PYTHON PROGRAMMING


Objectives

Understand computer programming concept using python language. Explore basic data types, control structures and standard library functions. Explore the basic data structures: List, Tuple, Sets, Dictionaries available in python. Learning Object oriented concept of programming and its implementation in python.

Learning Outcomes:

At the end of the course, students will be able to–

·         Solve the basic mathematical problem using python programming.

·         Use basic data types control structures and utility functions from standard library for faster programming.

·         Use the basic and user defined data structures as per the need of problem. Design and implement the problem using OOP concept of python.

Detailed Syllabus

Unit 1

8 classes

Introduction to Python: Introduction, The History of Python, Features of python

language, Getting Started with Python, Programming Style and Documentation,

Programming Errors.

Elementary Programming: Introduction, Writing a Simple Program, Reading

Input from the Console, Identifiers, Variables, Assignment Statements, and

Expressions, Simultaneous Assignments, Named Constants, Numeric Data Types

and Operators, Evaluating Expressions and Operator Precedence, Augmented

Assignment Operators, Type Conversions and Rounding.

Unit 2

7 classes

Control Structures: Selections: Introduction, Boolean Types, Values, and Expressions, if Statements, Two-Way if-else Statements, Nested if and Multi-Way

if-else if-else Statements, Logical Operators, Conditional Expressions, Loops:

Introduction, The while Loop, The for Loop, Nested Loops, Keywords break and

continue

Unit 3

10 classes

Functions: Introduction, Defining a Function, Calling a Function, Functions

with/without Return Values, Positional and Keyword Arguments, Passing

Arguments by Reference Values, Modularizing code, The Scope of Variables,

Default Arguments, Returning Multiple Values.

Lists: Introduction, List Basics, Copying Lists, Passing Lists to Functions,

Returning a List from a Function, Searching Lists, Sorting, Processing Two-

Dimensional Lists, Passing Two-Dimensional Lists to Functions,

Multidimensional Lists.

Unit 4

10 classes

Tuples, Sets, and Dictionaries: Introduction, Tuples: Creating Tuples, Basic

Tuple Operations, Indexing and Slicing in Tuples, Tuple methods, Sets: Creating

Sets, Manipulating and Accessing Sets, Subset and Superset, Set Operations,

Comparing the Performance of Sets and Lists, Dictionaries: Creating a Dictionary,

Adding, Modifying, and Retrieving Values, Deleting Items, Looping Items, The

Dictionary Methods.

Unit 5

10 classes

Objects and Classes: Introduction, Defining Classes for Objects, Immutable

Objects vs. Mutable Objects, Hiding Data Fields, Class Abstraction and

Encapsulation.

Inheritance and Polymorphism: Introduction, Super classes and Subclasses,

Overriding Methods, The object Class, Polymorphism and Dynamic Binding, The

is instance function. Class Relationships: Association, Aggregation, composition.

Files and Exception Handling: Introduction, text input and output: opening a file,

Writing Data, Reading All Data from a File, Exception Handling.



UNIT 5

OBJECTS AND CLASSES: INTRODUCTION

WHAT IS CLASSES:-   A class is a user defined entity (data types) OR template  OR A class is considered a blueprint of objects that defines the type of data an object can contain and the actions it can perform. It is used as a template for creating objects.

A class is considered 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; the house is the object.

Since many houses can be made from the same description, we can create many objects from a class.

RULES FOR THE CLASS CREATION :-

Syntax Rules

1.         Use the class keyword: All class definitions must start with the class keyword.

2          Use a Colon and Indentation: The class definition line must end with a colon (:), and the class body must be indented (typically four spaces).

3.         self as the first parameter: Instance methods must have their first parameter refer to the current object instance itself. The convention is to name this parameter self, which is automatically passed by Python when the method is called. (self means, self ke pass current object hai, means self ke pass es class ka object hota hai)

4.         _ _init_ _() method (constructor): two under score under score phale and two under score under score bad me yeh sab special method kahalata hai ( _ _ init _ _), This special "dunder" (double-underscore) method is automatically called when a new object is created (instantiated). It is used to initialize the object's attributes (instance variables) with starting values.

5          Non-empty body: A class body cannot be empty. If no attributes or methods are needed yet, use the pass statement as a placeholder to avoid an error.

6.         Class Names (PascalCase): Use PascalCase (or UpperCamelCase) for class names (e.g., MyClass, CarModel).

 

CREATING CLASSES IN PYTHON:- We use the class keyword to create a class in Python. For EXAMPLE,

class ClassName:

    # class definition

Here, we have created a class named ClassName.

 

Let's see an example,

class Bike:

    name = ""

    gear = 0

Here,

Bike - the name of the class

name/gear - variables inside the class with default values "" and 0 respectively.

NOTE: THE VARIABLES INSIDE A CLASS ARE CALLED ATTRIBUTES.

EXAMPLE : Python Class and Objects

# define a class , name as Bike

class Bike:

    name = ""

    gear = 0

# create object of class the as bike1

bike1 = Bike()

# access attributes and assign new values from the object

bike1.gear = 11

bike1.name = "Bullet  Bike"

print(f"Name: {bike1.name}, Gears: {bike1.gear} ")

OUTPUT:-

Name: Bullet Bike, Gears: 11

In the above example, we have defined the class named Bike with two attributes: name and gear.

We have also created an object bike1 of the class Bike.  Finally, we have accessed and modified the properties of an object using the . notation.

CREATE MULTIPLE OBJECTS OF PYTHON CLASS:-    We can also create multiple objects from a single class.

EXAMPLE:-

# define a class

class Employee:

# define a property

    employee_id = 0

 # create two objects of the Employee class

employee1 = Employee()

employee2 = Employee()

 # access property using employee1

employee1.employeeID = 1001

print(f"Employee ID: {employee1.employeeID}")

 # access properties using employee2

employee2.employeeID = 1002

print(f"Employee ID: {employee2.employeeID}")

OUTPUT

Employee ID: 1001

Employee ID: 1002

In the above example, we have created two objects employee1 and employee2 of the Employee class.



PYTHON METHODS :- We can also define a function inside a Python class. A Python function defined inside a class is called a method.

(A method is a function that is associated with an object or a class. It is defined within a class and operates on the data (attributes) of that class or its instances. Methods define the behavior and actions that objects of a class can perform)

EXAMPLE:-

# create a class

class Room:

    length = 0.0

    breadth = 0.0

   

    # method to calculate area

    def calculate_area(self):

        print("Area of Room =", self.length * self.breadth)

 

# create object of Room class

study_room = Room()

 

# assign values to all the properties

study_room.length = 42.5

study_room.breadth = 30.8

 

# access method inside class

study_room.calculate_area()

OUTPUT:-   Area of Room = 1309.0

NOTE:- In the above example, we have created a class named Room with:

Attributes: length and breadth

Method: calculate_area()

Here, we have created an object named study_room from the Room class. We then used the object to assign values to attributes: length and breadth.  Notice that we have also used the object to call the method inside the class,

study_room.calculate_area()  , ,  Here, we have used the . notation to call the method. Finally, the statement inside the method is executed.

CREATING A EMPTY CLASS:-

EXAMPLE 1:

class A:

            pass   # pass is a key word which will ignore of the execution part , means here we will give data members of the class later.

obj=A( )

OUTPUT :- NOTHING

EXAMPLE 2:

 class A:

            age=20

            print(age)  # Agar ham run karenge program ko to hamko result milega , jabki ham object nahi banaye hai

OUTPUT:-     20

EXAMPLE 3:

NOTE :- PYTHON ME EK AUTOMATIC CONSTRUCTOR  HOTA HAI, KI AGAR HAM OBJECT NAHI BHI BANAYEGE TO PYTHON OUTPUT DEGA, YEH constructor  HIDE RAHTA HAI, SEE BELOW (PYTHON CONSTRUCTORS)

class A:

def  _ _init_ _ (self): # two under score under score phale and two under score under score bad me yeh sab special method kahalata hai ( _ _ init _ _), yehi hai automatic constructor jo result deta hai without object. lekin yeha per ek problem hai ki ye default constructor ka values ko only one time hi use kar sakte hai. Agar more than one time call karna pdega to hamko phir se print karna padega.

            age=20

            print(age)  # Agar ham run karenge program ko to hamko result milega , jabki ham object nahi banaye hai

obj=A( ) # Ab hamko object bana kar self constructor ko call karna padega , other wise zero (nothing)  output ayaga , because constructor class ka members hota hai and class ka members ko call karne ke liye object ka jarurat padta hai. and yeh constructor  current object ko hi point karta hai. (yeha per self ek reference parameter hota ha jo ki kishi bhi python class ke ander  , agar aap koi bhi function ya method banate hai  to aap ko self likhna hi padega.

RE WRITE THE PROGRAM OF CLASS

  class A:

def  _ _init_ _(self):

 age=20

            print(age) 

obj=A( )  #This is 1st method to called the data members of the class (by the class Name)

print(obj.age)   #This is 2nd method to called the data members of the class (by the object)

print(A.age)   #This is 3rd method to called the data members of the class( by the class)

OUTPUT

10

10

10

NOW RUN THE PROGRAM


QUESTIONS WITH ANSWER FOR FINAL EXAM 2026

Q1.      WHAT IS OVERRIDING METHODS ? EXPLAIN WITH EXAMPLE:-

The Python method overriding refers to defining a method in a subclass with the same name as a method in its superclass. In this case, the Python interpreter determines which method to call at runtime based on the actual object being referred to. You can always override your parent class methods. One reason for overriding parent's methods is that you may want special or different functionality in your subclass.

Method overriding is nothing but a specific feature of object-oriented programming languages. It allows a subclass or child class to give the programme with certain attributes or a specific data implementation procedure that is already defined in the parent or superclass.

Method overriding allows a child class to modify functions defined by its family classes. When the same returns, parameters, or names are entered in the subclass as in the parent class, the subclass’s implementation method overrides the parent class’s method. Method overriding is the term for this. In other words, the child class gets access to the parent class method’s properties and functions while also extending its own functions to the method.

Its execution is determined by the data used to call the method, rather than the reference data provided by the parent class. When a method in a subclass has the same name, parameters or signature, and return type (or sub-type) as a method in its super-class, the subclass method is said to override the super-class method. When a parent class object is used to call a program’s implementation method, the parent class’s version of the method is called.

 Example:-

class Shape:

    def no_of_sides(self):

        print("This shape has many sides")

class Square(Shape):

    def no_of_sides(self):

        print("A square has 4 sides")

 # Creating objects

s1 = Shape()

s2 = Square()

 # Calling the method

s1.no_of_sides()   # Parent class method

s2.no_of_sides()   # Child class overrides the method

 

OUTPUT

This shape has many sides

A square has 4 sides

Method Overriding Characteristics:-

  1. Method overriding in Python allows you to use functions and methods with the same name or signature.
  2. This method cannot be done in the same class. And overriding can only be done when a child class is derived through inheritance.
  3. Runtime polymorphism is certainly exemplified through method overloading.
  4. The child class should have the same name as the parent class and the same amount of arguments.
  5. By using the inheritance feature in python is always required when overriding a method.
  6. The object being invoked determines whether a parent class or child class method is invoked.
  7. Between parent and child classes, method overloading takes place.
  8. An overridden method’s execution is determined by the reference object.
  9. It’s used to alter existing methods’ behaviour and implementation.
  10. For method overriding, a minimum of two classes is always required.

Advantages Of Method Overriding:-

  • Overriding methods allow a user to modify the behaviour of already existent methods. To implement it, at least two classes are required.
  • The fundamental benefit of method overriding is that it allows the main class to declare methods that are shared by all. And the subclasses while also allowing subclasses to define their own unique implementations of any or all of those methods.
  • Inheritance is also required when overriding a method.
  • The child class function should have the same signature as the parent class function. This means it should have the same amount of parameters. In the case of method overriding, inheritance is required.
  • It refers to a child class’s ability to change the implementation of any method given by one of its parent classes.

Q2       DIFFERENCE BETWEEN IMMUTABLE OBJECTS VS. MUTABLE OBJECTS

Aspect

Mutable Objects

Immutable Objects

Definition

Objects whose state or value can be changed after they are created.

Objects whose state or value cannot be changed once they are created.

Examples

Lists, Dictionaries, Sets

Integers, Floats, Strings, Tuples,

Memory Allocation

Can modify in place without creating a new object.

Creating a new object is required when attempting to modify.

Behavior with Assignment

Assigning a new reference does not affect other references.

Assigning a new reference creates a new object, leaving the original unchanged.

Efficiency

More memory efficient as they allow changes without allocating new memory.

Less memory efficient as new objects are created for any modification.

Impact on Functions

Functions can alter the original object, affecting other references to it.

Functions cannot alter the original object, ensuring it remains unchanged.

Use Cases

Ideal for situations where changes to the object are frequent, e.g., dynamic data storage.

Ideal when the object should remain constant throughout the program, e.g., keys in dictionaries, constants.

Example of Mutation

list1 = [1, 2, 3]

list1[0] = 10 modifies the object.

string1 = "hello"

string1[0] = "H" results in an error.

Thread Safety

Not thread-safe, as changes to mutable objects can lead to inconsistent state in multi-threaded programs.

Thread-safe, as immutable objects cannot be altered after creation, ensuring consistency.




Q3       WHAT IS FILE HANDLING? WRITE ALL THE STEPS TO OPEN A TEXT FILE , READ THE FILE AND WRITE:-

 INTRODUCTION TO FILES:- We have so far created programs in Python that accept the input, manipulate it and display the output. But that output is available only during execution of the program and input is to be entered through the keyboard. This is because the variables used in a program have a lifetime that lasts till the time the program is under execution. What if we want to store the data that were input as well as the generated output permanently so that we can reuse it later? Usually, organisations would want to permanently store information about employees, inventory, sales, etc. to avoid repetitive tasks of entering the same data. Hence, data are stored permanently on secondary storage devices for reusability. We store Python programs written in script mode with a .py extension. Each program is stored on the secondary device as a file. Likewise, the data entered, and the output can be stored permanently into a file.

FILE HANDLING:-

File handling is the process of creating, reading, writing, and managing files in a program. It is a fundamental skill in programming that helps to store, retrieve, and manipulate data efficiently. Proper file handling ensures that programs are robust, secure, and maintainable, especially when dealing with user-generated content, large datasets, or configuration files. Proper file handling also enables structured data organization, which is essential for large-scale and repeated operations.

TYPES OF FILES:-Computers store every file as a collection of 0 s and 1 s  i.e., in binary form. There are mainly two types of data files - text file and binary file. 

(1).       Text file:- A text file can be understood as a sequence of characters consisting of alphabets, numbers and other special symbols. Files with extensions like .txt, .py, .csv, etc. are some examples of text files. When we open a text file using a text editor (e.g., Notepad), we see several lines of text. However, the file contents are not stored in such a way internally. Rather, they are stored in sequence of bytes consisting of  0 s and 1 s. In ASCII, UNICODE or any other encoding scheme, the value of each character of the text file is stored as bytes. So, while opening a text file, the text editor translates each ASCII value and shows us the equivalent character that is readable by the human being. For example, the ASCII value 65 (binary equivalent 1000001) will be displayed by a text editor as the letter ’ A ’ since the number 65 in ASCII character set represents ’ A  ‘.

(2)        Binary Files:- Binary files are also stored in terms of bytes (0s and 1s), but unlike text files, these bytes do not represent the ASCII values of characters. Rather, they represent the actual content such as image, audio, video, compressed versions of other files, executable files, etc. These files are not human readable. Thus, trying to open a binary file using a text editor will show some garbage values. We need specific software to read or write the contents of a binary file.

Binary files are stored in a computer in a sequence of bytes. Even a single bit change can corrupt the file and make it unreadable to the supporting application. Also, it is difficult to remove any error which may occur in the binary file as the stored contents are not human readable. We can read and write both text and binary files through Python programs.

MODES OF FILE HANDLING IN PYTHON:-

Here are the most commonly used file handling modes in Python:

1. Read Mode 'r': The read mode is denoted by the character 'r', and it's used when you want to open a file for reading its contents.We cannot modify the file using this mode.

2. Write Mode 'w': This mode is used to write data to a file. If files do not exist,it will get created. If it already exists, contents will be overwritten. If you want to append data to the existing file content, you can use the 'a' mode instead.

3. Append Mode 'a’: This mode is used to append data to an existing file.File will be created if not present earlier. The new data will be added to the end of the existing file content, without overwriting it.

4. Binary Mode 'b’:Binary files like images,videos,audios can be handled here. For example, 'rb' is used to read a binary file, and 'wb' is used to write to a binary file.

5. Exclusive Creation Mode 'x': This mode is used to create a new file, but it raises a FileExistsError if the file already exists.


6. Update Mode '+': This mode is used to open a file for both reading and writing. It is added to the other modes. For example, 'r+' is used to open a file for both reading and writing.

 

To use these modes, you can pass them as the second argument when using the open() function to open a file.

For example:-

Open a file in read mode

file=open(‘example.txt’,’r’)

Open a file in write mode

file=open(‘example.txt’,’w’)

Open a file in append mode

file=open(‘example.txt’,’a’)

Open a binary file in read mode

file=open(‘example.bin’,’rb’)

Open a file in both reading and writing mode

file=open(‘example.txt’,’r+’)

file.close()

OPENING A FILE:-

To open a file in Python, we use the open() function. The syntax of open() is as follows:

file_object= open(file_name, access_mode)

 

CLOSING A FILE:-

Once we are done with the read / write operations on a file, it is a good practice to close the file. Python provides a close () method to do so. While closing a file, the system frees the memory allocated to it. The syntax of close () is:

file_object.close ()

Here, file_object is the object that was returned while opening the file.

THE WRITE() METHOD:-

write() method takes a string as an argument and writes it to the text file. It returns the number of characters being written on single execution of the write() method. Also, we need to add a newline character (\n) at the end of every sentence to mark the end of line.

Consider the following piece of code:

>>> myobject=open(“myfile.txt”,‘w’)

>>> myobject.write(“Hey I have started #using fi les in Python\n”)

41

>>> myobject.close()

On execution, write() returns the number of characters written on to the file. Hence, 41, which is the length of the string passed as an argument, is displayed.

Note: ’ \n ’ is treated as a single character if numeric data are to be written to a text file, the data need to be converted into string before writing to the file.

For example:-

>>> myobject=open(“myfile.txt”,‘w’)

>>> marks=58

#number 58 is converted to a string using

#str()

>>> myobject.write(str(marks))

2

>>> myobject.close()

The write() actually writes data onto a buffer. When the close() method is executed, the contents from this buffer are moved to the file located on the permanent storage.



We can also use the ush() method to clear the buffer and write contents in buffer to the file. This is how programmers can forcefully write to the file as and when required.

 

THE READ() METHOD:-

This method is used to read a specified number of bytes of data from a data file. The syntax of read() method is: le_object.read(n)

Consider the following set of statements to understand the usage of read() method:

>>> myobject=open(“myfile.txt”,‘r’)

>>> myobject.read(10)

‘Hello ever’

>>> myobject.close()

 

If no argument or a negative number is specified in read(), the entire file content is read.

For example:-

>>> myobject=open(“myfile.txt”,‘r’)

>>> print(myobject.read())

Hello everyone

Writing multiline strings

This is the third line

>>> myobject.close()


Q4.      EXPLAIN WITH EXAMPLE :- CLASS RELATIONSHIPS: ASSOCIATION, AGGREGATION, COMPOSITION

WHAT IS ASSOCIATION:- Association is an Object-Oriented Programming (OOP) concept that defines a relationship between two or more classes, where objects of one class are connected to objects of another class for performing some task, but both classes remain independent.

In Association:-

One class uses the object of another class, There is no strong ownership, Objects can exist independently, Relationship is created at runtime, It represents a “uses-a” relationship

 

Real-Life Examples of Association:-

Teacher – Student:- Teacher teaches student, both exist independently

Doctor – Patient:- Doctor treats patient, both are independent

Library – Book:- Library uses books, books can exist outside library

Company – Employee:- Company uses employees, employees exist independently

TYPES OF ASSOCIATION:-

Association is mainly divided into two types:-

(1)        One-Way Association (Unidirectional):- In one-way association, only one class knows about the other class, but the second class does not know about the first. Means, Relationship flows in one direction, One class uses another class

Example::- Teacher → Student

class Student:

    def _ _init_ _(self, name):

        self.name = name

     def show_student(self):

print("Student Name:", self.name)

 

class Teacher:

    def _ _init_ _(self, teacher_name, student):

        self.teacher_name = teacher_name

        self.student = student   # Association

 

    def show_details(self):

        print("Teacher Name:", self.teacher_name)

        self.student.show_student()

 

# Creating Student object

s1 = Student("Ajay")

 # Creating Teacher object and passing Student object

t1 = Teacher("Mr. Kumar", s1)

t1.show_details()

OUTPUT

Teacher Name: Mr. Kumar

Student Name: Ajay



(2) Two-Way Association (Bidirectional):- In two-way association, both classes know about each other and both can access each other’s data.

Example:- Doctor ↔ Patient

class Doctor:

    def __init__(self, name):

        self.name = name

 

    def show_doctor(self):

        print("Doctor Name:", self.name)

 

class Patient:

    def __init__(self, name, doctor):

        self.name = name


        self.doctor = doctor   # Association

 

    def show_patient(self):

        print("Patient Name:", self.name)

        self.doctor.show_doctor()

 # Creating Doctor object

d1 = Doctor("Dr. Sharma")

 # Creating Patient object and passing Doctor object

p1 = Patient("Ravi", d1)

p1.show_patient()

OUTPUT

Patient Name: Ravi

Doctor Name: Dr. Sharma

Association Example with Multiple Objects:-

class Engine:

    def start(self):

        print("Engine started")

 

class Car:

    def __init__(self, engine):

        self.engine = engine  # Association

 

    def drive(self):

        self.engine.start()

        print("Car is moving")

e1 = Engine()

c1 = Car(e1)

c1.drive()



Advantages of Association:-

1.      Improves code reusability

2.      Loose coupling

3.      Easy to maintain

4.      Real-world modeling

5.      Flexible design

Disadvantages of Association

1.      Can increase program complexity

2. Hard to manage in large systems

WHAT IS  AGGREGATION IN PYTHON (OBJECT-ORIENTED PROGRAMMING):-

Aggregation is an Object-Oriented Programming (OOP) concept that represents a “has-a” relationship between two classes, where one class contains the object of another class, but both classes can exist independently.

OR Aggregation is a special type of association that represents a weak “has-a” relationship where the lifetime of contained objects is independent of the container object.

In Aggregation:-

ü  One class is a container (whole)

ü  Another class is a contained (part)

ü  The contained object can exist without the container

ü  Ownership is weak

ü  Relationship is long-term, not temporary like association

Explanation in Simple Words:-

Aggregation means:-

One object has another object

But does not fully own it

If the main object is deleted, the child object still survives

 Real-Life Examples of Aggregation:-

Whole (Container)

Part (Contained)

Explanation

Department

Teacher

Teacher exists even if department is removed

Library

Book

Book can exist without lib

School

Student 

Student can exist without school            

Team

Player

Player exists independently                 


TYPES OF AGGREGATION:-

Aggregation is mainly divided into two types:-

(1)        Shared Aggregation:- In shared aggregation, the same object is shared among multiple container objects.

Meaning:- One object belongs to multiple objects, Object is not owned by any one container

Example:- One Teacher works in multiple Departments

Example of program

class Teacher:

    def __init__(self, name):

        self.name = name

 

    def show_teacher(self):

        print("Teacher Name:", self.name)

 

class Department:

    def __init__(self, dept_name, teacher):

        self.dept_name = dept_name

        self.teacher = teacher  # Aggregation

 

    def show_department(self):

        print("Department Name:", self.dept_name)

        self.teacher.show_teacher()

 

# One teacher object

t1 = Teacher("Mr. Sharma")

 

# Same teacher in two departments

d1 = Department("Computer Science", t1)

d2 = Department("Information Technology", t1)

 

d1.show_department()

d2.show_department()

OUTPUT

Department Name: Computer Science

Teacher Name: Mr. Sharma

Department Name: Information Technology

Teacher Name: Mr. Sharma

(2)        Non-Shared Aggregation:- In non-shared aggregation, the contained object is used by only one container, but it still exists independently.

Example:- Library has Books (each book used by one library)

Example program (Non-Shared Aggregation)

class Book:

    def __init__(self, title):

        self.title = title

     def show_book(self):

        print("Book Title:", self.title)

  class Library:

    def __init__(self, library_name, book):

        self.library_name = library_name

        self.book = book  # Aggregation

     def show_library(self):

        print("Library Name:", self.library_name)

        self.book.show_book()

  b1 = Book("Python Programming")

L1 = Library("Central Library", b1)

L1.show_library()

Advantages of Aggregation:-

(1 )Objects can be reused

(2) Better modular design

(3)  Loose coupling

(4)  Real-world relationship modeling

Disadvantages of Aggregation

(1)   More complex than association

(2) Object management can be difficult


WHAT IS COMPOSITION:-

COMPOSITION IN PYTHON (Object-Oriented Programming):- Composition is an Object-Oriented Programming (OOP) concept that represents a strong “has-a” relationship between two classes, where one class completely owns another class and controls its lifetime.

OR

Composition is a strong form of association in which one class contains and owns another class, and the lifetime of the contained object depends completely on the container object.

In Composition:

·         One class is the owner (whole)

·         Another class is the part

·         The part cannot exist without the whole

·         Ownership is strong

·         When the container object is destroyed, the contained object is automatically destroyed

Real-Life Examples of Composition:-

Whole (Owner)

Part (Owned)

Explanation

House

Room

Room cannot exist without house 

Car

Engine

Engine is part of car           

Human

Heart

Heart cannot exist without human

Computer

CPU

CPU is part of computer         


TYPES OF COMPOSITION:-

Composition can be classified into two main types (for theory clarity):

(1)        Mandatory Composition:- In mandatory composition, the part object must exist for the whole object to exist. Whole cannot function without the part, Part is compulsory

Example:- Car must have an Engine

Easy Python Program (Mandatory Composition)

class Engine:

    def __init__(self):

        print("Engine created")

     def start(self):

        print("Engine started")

 class Car:

    def __init__(self):

        self.engine = Engine()   # Composition

     def drive(self):

        self.engine.start()

        print("Car is moving")

 c1 = Car()

c1.drive()

OUTPUT

Engine created

Engine started

Car is moving



Optional Composition:- In optional composition, the part object may or may not exist, but if it exists, its lifetime depends on the whole.

Example:- Mobile phone may have Camera

Easy Python Program (Optional Composition):-

class Camera:

    def take_photo(self):

        print("Photo taken")

  class Mobile:

    def __init__(self, has_camera=True):

        if has_camera:

            self.camera = Camera()   # Composition

        else:

            self.camera = None

     def use_camera(self):

        if self.camera:

            self.camera.take_photo()

        else:

            print("No camera available")

 m1 = Mobile(True)

m1.use_camera()

m2 = Mobile(False)

m2.use_camera()

Advantages of Composition

i.        Strong data security

ii.      Better control over objects

iii.    Clear ownership

iv.    Good for real-world modeling

Disadvantages of Composition

i.        Tight coupling

ii.      Less flexible than aggregation

iii.    Reuse of part object is limited


WHAT IS DYNAMIC BINDING?

Dynamic binding, also known as late binding, is a fundamental feature in Python that allows method calls and variable references to be resolved at runtime rather than compile-time. This flexibility is primarily a result of Python's dynamic typing and its object-oriented nature, which supports polymorphism. 

In dynamic binding, the method that gets executed is determined by the actual object type at the moment the method is called, rather than the type of the reference variable that holds the object.

For example:-

Consider a scenario where a superclass defines a method, and a subclass overrides that method. If you create an instance of the subclass and call the overridden method, Python will dynamically bind the method call to the subclass implementation, even if the reference is of the superclass type. This allows for more flexible and reusable code, as you can write functions or methods that operate on objects of different classes without knowing their specific types beforehand. 

Dynamic binding is particularly useful in frameworks and libraries that utilize callbacks, event handling, or any situation where behavior may vary based on object types at runtime.

 TYPES OF DYNAMIC BINDING:-

(1)        Method Overriding Based Dynamic Binding:- When a child class provides its own implementation of a method that already exists in the parent class, and the method call is resolved at runtime, it is called Dynamic Binding using Method Overriding.

Easy Example:-

class Animal:

    def sound(self):

        print("Animal makes a sound")

 class Dog(Animal):

    def sound(self):

        print("Dog barks")

 class Cat(Animal):

    def sound(self):

        print("Cat meows")

 # Parent reference, child objects

a1 = Dog()

a2 = Cat()

 a1.sound()

a2.sound()

OUTPUT

Dog barks

Cat meows



(2)        Dynamic Binding using Parent Class Reference:- When a parent class reference variable points to a child class object, and the method call is resolved at runtime, it is called Dynamic Binding using parent reference.

 Easy Example:-

class Shape:

    def draw(self):

        print("Drawing a shape")

 class Circle(Shape):

    def draw(self):

        print("Drawing a circle")

 class Square(Shape):

    def draw(self):

        print("Drawing a square")

 

# Same reference, different objects

shape = Circle()

shape.draw()

 shape = Square()

shape.draw()

 class Shape:

    def draw(self):

        print("Drawing a shape")

 class Circle(Shape):

    def draw(self):

        print("Drawing a circle")

 class Square(Shape):

    def draw(self):

        print("Drawing a square")

 # Same reference, different objects

shape = Circle()

shape.draw()

 shape = Square()

shape.draw()

 OUTPUT

Drawing a circle

Drawing a square

Advantages of Dynamic Binding:-

 

i.        Supports polymorphism

ii.      Makes code flexible

iii.    Improves reusability

iv.    Easy to extend programs

v.      Runtime decision making

 

Disadvantages of Dynamic Binding:-

 

i.        Slightly slower execution

ii.      Errors appear at runtime

iii.    Harder to debug large programs



THE END









No comments:

Post a Comment

PLEASE DO LEAVE YOUR COMMENTS

UNIT 5 SOFTWARE TESTING (UNIT NAME) :- TEST AUTOMATION TOOLS AND EMERGING TRENDS

  DR. AJAY KUMAR PATHAK  ASSISTANT PROFESSOR READ  ALL THE NOTES CHAPTER WISE   MINOR PAPER   SUBJECT NAME:-   MN–2C (Th):- SOFTWARE TESTING...