[go: up one dir, main page]

0% found this document useful (0 votes)
5 views25 pages

Unit-4 Web and Internet Technology

The document covers key concepts in Object-Oriented Programming (OOP) including Abstract Data Types (ADTs), classes, objects, inheritance, encapsulation, file handling, and exception handling in Python. It explains how ADTs define data behavior, how classes implement these types, and the importance of inheritance for code reuse and structure. Additionally, it discusses file operations, exception management, and provides insights into using MySQL with Python for database interactions.

Uploaded by

sharmaabhi12755
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)
5 views25 pages

Unit-4 Web and Internet Technology

The document covers key concepts in Object-Oriented Programming (OOP) including Abstract Data Types (ADTs), classes, objects, inheritance, encapsulation, file handling, and exception handling in Python. It explains how ADTs define data behavior, how classes implement these types, and the importance of inheritance for code reuse and structure. Additionally, it discusses file operations, exception management, and provides insights into using MySQL with Python for database interactions.

Uploaded by

sharmaabhi12755
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/ 25

Topic: Classes and Object-Oriented Programming

Subtopic: Abstract Data Types and Classes

1. What is Object-Oriented Programming (OOP)?


Object-Oriented Programming (OOP) is a programming paradigm that organizes code using
classes and objects, enabling better modularity, reusability, and scalability.

2. Abstract Data Types (ADTs)


An Abstract Data Type is a model for data structures that defines the behavior (operations)
without specifying how the data is implemented.

Examples of ADTs:

●​ Stack​

●​ Queue​

●​ Linked List​

●​ Tree​

These structures focus on what operations are available (e.g., push, pop), not how they are
implemented internally.

3. Defining ADTs with Classes in Python


In Python, ADTs are implemented using classes. A class bundles data (attributes) and
functions (methods) into one structure.

Example: Stack as an ADT


class Stack:
def __init__(self):
self.items = []

def push(self, item):


self.items.append(item)

def pop(self):
if not self.is_empty():
return self.items.pop()

def is_empty(self):
return len(self.items) == 0

Here:

●​ push() and pop() are the behaviors.​

●​ items is the internal structure (not exposed directly).​

4. What is a Class?
A class is a blueprint for creating objects. It defines the structure (attributes) and behavior
(methods) of its objects.

Syntax:
class ClassName:
def __init__(self, parameters):
self.attribute = value

def method(self):
# behavior

5. What is an Object?
An object is an instance of a class.

Example:
class Person:
def __init__(self, name):
self.name = name

def greet(self):
print(f"Hello, I am {self.name}")

p1 = Person("Vishal")
p1.greet() # Output: Hello, I am Vishal

Summary
●​ ADTs define how data can be used, not how it is implemented.​

●​ Classes implement ADTs by bundling data and behavior.​

●​ Objects are instances of classes used to interact with real-world entities in code.​

Topic: Inheritance in Python (Object-Oriented Programming)

1. What is Inheritance?
Inheritance is a feature of Object-Oriented Programming (OOP) that allows a class to inherit
properties and behaviors (methods and attributes) from another class.

●​ The class that is inherited from is called the Parent (or Base) class.​

●​ The class that inherits is called the Child (or Derived) class.​

2. Why Use Inheritance?


●​ Code Reusability: Reuse existing code without rewriting it.​

●​ Extensibility: Add new features to existing classes.​


●​ Maintainability: Easier to update and manage code.​

3. Basic Syntax
class Parent:
def speak(self):
print("I am the parent")

class Child(Parent):
pass

obj = Child()
obj.speak() # Output: I am the parent

Here, Child inherits the speak() method from Parent.

4. Method Overriding
The child class can override the parent’s method by defining it again.

class Parent:
def greet(self):
print("Hello from Parent")

class Child(Parent):
def greet(self):
print("Hello from Child")

obj = Child()
obj.greet() # Output: Hello from Child

5. The super() Function


The super() function is used in a child class to call a method from the parent class.

class Parent:
def show(self):
print("Parent class")

class Child(Parent):
def show(self):
super().show()
print("Child class")

obj = Child()
obj.show()

Output:

Parent class
Child class

6. Types of Inheritance in Python

Type Description

Single Inheritance One child inherits from one parent

Multiple Inheritance One child inherits from more than one parent

Multilevel Inheritance A class inherits from a child of another class

Hierarchical Inheritance Multiple children inherit from the same parent

Hybrid Inheritance Combination of two or more types above


Example of Multiple Inheritance:

class A:
def methodA(self):
print("Method A")

class B:
def methodB(self):
print("Method B")

class C(A, B):


pass

obj = C()
obj.methodA()
obj.methodB()

Summary
●​ Inheritance allows code reuse and logical structure.​

●​ Child classes can inherit, override, or extend parent class behavior.​

●​ Python supports multiple types of inheritance, making it flexible for OOP design.​

Topic: Encapsulation and Information Hiding in Python

1. What is Encapsulation?
Encapsulation is an Object-Oriented Programming (OOP) concept that means bundling data
(variables) and methods (functions) into a single unit — the class.

It helps protect an object’s internal state and only allows controlled access through methods.
Benefits of Encapsulation:

●​ Protects data from unintended access or modification.​

●​ Promotes modular, organized, and maintainable code.​

●​ Allows information hiding.​

2. Information Hiding
Information hiding means restricting access to certain parts of an object’s data, exposing only
what is necessary. This is done using access modifiers.

3. Access Modifiers in Python


Python does not enforce strict access control, but uses naming conventions:

Modifier Type Syntax Meaning

Public self.name Accessible from anywhere

Protected self._name Should not be accessed outside class (by


convention)

Private self.__nam Not accessible directly from outside


e

Example:
class Person:
def __init__(self, name, age):
self.name = name # Public
self._age = age # Protected
self.__salary = 50000 # Private

def show_info(self):
print(f"Name: {self.name}, Age: {self._age}")

p = Person("Ravi", 30)
print(p.name) # Allowed
print(p._age) # Allowed (but discouraged)
# print(p.__salary) # Error (private)

# Accessing private variable (not recommended):


print(p._Person__salary)

4. Using Getters and Setters (Access Methods)


To access or update private data safely, we use getters and setters:

class Employee:
def __init__(self):
self.__salary = 0

def set_salary(self, amount):


if amount > 0:
self.__salary = amount

def get_salary(self):
return self.__salary

emp = Employee()
emp.set_salary(60000)
print(emp.get_salary()) # Output: 60000

Summary
●​ Encapsulation groups data and methods into one unit (class).​

●​ Information hiding limits direct access to internal variables.​

●​ Python uses naming conventions to control access:​


○​ public: accessible everywhere​

○​ _protected: for internal use​

○​ __private: hidden from outside​

●​ Use getters and setters to access private data safely.​

Topic: File Handling in Python

1. What is File Handling?


File handling in Python allows you to create, read, write, and delete files. It is essential for
storing data permanently (outside of memory).

Python provides built-in functions to work with files using the open() function.

2. File Modes in Python

Mode Description

'r' Read (default mode)

'w' Write (overwrites file)

'a' Append (adds to file)

'x' Create (fails if file exists)


'b' Binary mode (e.g., 'rb')

't' Text mode (default, e.g., 'rt')

3. Opening a File
file = open("example.txt", "r") # Open for reading

4. Reading from a File


content = file.read() # Reads entire content
line = file.readline() # Reads one line
lines = file.readlines() # Reads all lines as a list

Don’t forget to close the file:

file.close()

5. Writing to a File
file = open("example.txt", "w")
file.write("Hello, world!")
file.close()

Use "a" mode to append instead of overwrite:

file = open("example.txt", "a")


file.write("\nNew line added.")
file.close()

6. Using with Statement (Recommended)


Automatically closes the file after operations:

with open("example.txt", "r") as file:


data = file.read()
print(data)

7. Deleting Files (Using os module)


import os

# Check if file exists


if os.path.exists("example.txt"):
os.remove("example.txt")
else:
print("File not found.")

Summary
●​ Use the open() function with correct mode ('r', 'w', 'a', etc.).​

●​ Always close files after use or use with open(...) for safer handling.​

●​ Use os.remove() to delete files if needed.​

Topic: Exception Handling in Python

1. What is an Exception?
An exception is an error that occurs during the execution of a program, which interrupts the
normal flow of instructions.

Examples:

●​ Dividing by zero​

●​ Accessing an invalid index​

●​ Opening a file that doesn’t exist​


2. Why Use Exception Handling?
●​ To prevent the program from crashing.​

●​ To handle errors gracefully and display custom messages.​

●​ To keep the program running even if an error occurs.​

3. Basic Syntax of Exception Handling


try:
# Code that may cause an exception
except ExceptionType:
# Code that runs if exception occurs

Example:
try:
x = 10 / 0
except ZeroDivisionError:
print("You can't divide by zero!")

Output:

You can't divide by zero!

4. Multiple Except Blocks


try:
num = int(input("Enter a number: "))
result = 10 / num
except ValueError:
print("Invalid input! Please enter a number.")
except ZeroDivisionError:
print("Cannot divide by zero.")
5. The else Clause
Executes if no exception occurs:

try:
x=5
y=2
result = x / y
except ZeroDivisionError:
print("Error: Division by zero")
else:
print("Division successful:", result)

6. The finally Clause


Executes no matter what (whether exception occurred or not):

try:
f = open("test.txt", "r")
except FileNotFoundError:
print("File not found.")
finally:
print("Execution completed.")

7. Raising Custom Exceptions


You can raise your own exceptions using raise:

age = 15
if age < 18:
raise ValueError("Age must be at least 18")

Summary
●​ Use try and except to handle exceptions.​

●​ Use else to run code only if no exception occurs.​

●​ Use finally to clean up resources.​


●​ Handle specific exceptions like ValueError, ZeroDivisionError, FileNotFoundError, etc.​

●​ Custom exceptions can be raised using raise.​

1. Introduction
MySQLdb is a Python library used to interact with MySQL databases. It allows you to connect
to a MySQL server, create tables, insert, delete, and retrieve data using Python.

To use MySQLdb, you must install it using:


pip install mysqlclient

2. Connecting to a MySQL Database


import MySQLdb

db = MySQLdb.connect(
host="localhost",
user="root",
passwd="yourpassword",
database="yourdatabase"
)

cursor = db.cursor()

3. Checking if a File (Table) Exists


cursor.execute("SHOW TABLES LIKE 'students'")
result = cursor.fetchone()

if result:
print("Table exists.")
else:
print("Table does not exist.")

4. Creating a Table
cursor.execute("""
CREATE TABLE IF NOT EXISTS students (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
age INT
)
""")

5. Inserting Data
cursor.execute("INSERT INTO students (name, age) VALUES
(%s, %s)", ("Ravi", 20))
db.commit()

6. Deleting Data
cursor.execute("DELETE FROM students WHERE name = %s",
("Ravi",))
db.commit()

7. Fetching Data
cursor.execute("SELECT * FROM students")
rows = cursor.fetchall()

for row in rows:


print(row)
8. Closing the Connection
db.close()

9. Regular Expressions in Python (re module)


Used for pattern matching in strings.

import re

text = "Email: test@example.com"


pattern = r"\w+@\w+\.\w+"

match = re.search(pattern, text)


if match:
print("Found:", match.group())

10. Plotting in Python


Used for visualizing data using libraries like matplotlib.

import matplotlib.pyplot as plt

x = [1, 2, 3, 4]
y = [10, 20, 30, 40]

plt.plot(x, y)
plt.title("Sample Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()
Summary
●​ MySQLdb is used to connect Python with MySQL
databases.​

●​ You can perform CRUD operations (Create, Read, Update,


Delete) easily.​

●​ Use the re module for regular expressions and matplotlib for


plotting data.​

●​ Always remember to commit changes and close


connections.​

1. File (Table) Check in MySQL


Before creating a table, it’s good practice to check if it already
exists

import MySQLdb

# Connect to the database


db = MySQLdb.connect(host="localhost", user="root",
passwd="yourpassword", database="yourdatabase")
cursor = db.cursor()

# Check if table exists


cursor.execute("SHOW TABLES LIKE 'students'")
result = cursor.fetchone()
if result:
print("Table exists.")
else:
print("Table does not exist.")

2. Table Creation
If the table does not exist, you can create it using SQL:

cursor.execute("""
CREATE TABLE IF NOT EXISTS students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
age INT
)
""")
print("Table created successfully.")

3. Inserting Data into the Table


To insert records into the table:

# Insert one record


cursor.execute("INSERT INTO students (name, age) VALUES
(%s, %s)", ("Ravi", 22))

# Insert multiple records


students = [("Aman", 21), ("Neha", 23), ("Priya", 20)]
cursor.executemany("INSERT INTO students (name, age)
VALUES (%s, %s)", students)
# Save changes
db.commit()
print("Data inserted successfully.")

4. Deleting Data from the Table


To remove records based on a condition:

cursor.execute("DELETE FROM students WHERE name = %s",


("Ravi",))
db.commit()
print("Data deleted successfully.")

To delete all data (but keep the table structure):

cursor.execute("DELETE FROM students")


db.commit()

To drop the table completely:

cursor.execute("DROP TABLE IF EXISTS students")


print("Table deleted.")

5. Closing the Connection


Always close the database connection at the end:

db.close()
Summary
●​ Use SHOW TABLES to check for table existence.​

●​ CREATE TABLE to define new tables.​

●​ Use INSERT INTO for adding data and DELETE FROM to


remove data.​

●​ Always commit changes and close the connection.​

Topic: Regular Expressions (re module) in Python and Plotting

Part 1: Regular Expressions in Python

1. What is a Regular Expression?

A Regular Expression (regex) is a special sequence of


characters that helps match or find patterns in strings.

Python provides the re module to work with regular expressions.


2. Basic Functions in re Module

Functi Description
on

re.sear Searches for the first match


ch() in a string

re.mat Matches only at the


ch() beginning of the string

re.find Returns a list of all matches


all()

re.sub( Replaces matched patterns


)

3. Common Patterns

Patte Description
rn

\d Digit (0–9)
\w Word character (a-z,
A-Z, 0-9)

\s Whitespace

. Any character except


newline

^ Start of string

$ End of string

[] Matches any one


character in set

4. Example: Finding an Email


import re

text = "Contact: test123@example.com"


pattern = r"\w+@\w+\.\w+"

match = re.search(pattern, text)


if match:
print("Found:", match.group())

5. Replacing Text Using re.sub()


import re

text = "Python is fun. Python is powerful."


new_text = re.sub("Python", "Java", text)
print(new_text)

Part 2: Plotting in Python using matplotlib

1. Introduction to Plotting

Plotting helps you visualize data using graphs like line plots, bar
charts, histograms, etc.

Use the matplotlib.pyplot module.

pip install matplotlib

2. Simple Line Plot


import matplotlib.pyplot as plt

x = [1, 2, 3, 4]
y = [10, 20, 25, 30]

plt.plot(x, y)
plt.title("Simple Line Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()
3. Bar Chart Example
names = ['A', 'B', 'C']
scores = [80, 70, 90]

plt.bar(names, scores)
plt.title("Scores")
plt.ylabel("Marks")
plt.show()

4. Histogram Example
data = [20, 20, 30, 40, 50, 50, 50, 60, 70]

plt.hist(data, bins=5)
plt.title("Distribution")
plt.xlabel("Values")
plt.ylabel("Frequency")
plt.show()

5. Pie Chart Example


labels = ['Python', 'Java', 'C++']
sizes = [50, 30, 20]

plt.pie(sizes, labels=labels, autopct='%1.1f%%')


plt.title("Language Popularity")
plt.show()
Summary
●​ Use re for pattern matching, searching, and replacing in
strings.​

●​ matplotlib.pyplot is used for plotting data visually using line


graphs, bar charts, pie charts, and more.​

You might also like