0% found this document useful (0 votes)
6 views13 pages

Python OOP Concepts and Exception Handling

Uploaded by

013579ria
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)
6 views13 pages

Python OOP Concepts and Exception Handling

Uploaded by

013579ria
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

1.

GUI — Explain (1 mark)


GUI (Graphical User Interface): Visual interface allowing user interaction via windows,
buttons, menus, icons instead of text commands. Makes programs user-friendly.

2. Polymorphism — Explain (8 marks)


Definition: Polymorphism = “many forms”. Same method name can perform different
behaviors depending on the object/type. Types:

 Compile-time (method overloading — not native in Python).


 Runtime (method overriding).
 Duck typing (any object with required method is accepted). Advantages: cleaner
code, easier extension, supports polymorphic interfaces. Example (Python):

class Bird: def fly(self): return "some fly" class Sparrow(Bird): def fly(self): return
"Sparrow flies" class Penguin(Bird): def fly(self): return "Penguins can't fly" def
let_it_fly(b): print([Link]()) let_it_fly(Sparrow()) # Sparrow flies let_it_fly(Penguin()) #
Penguins can't fly

3. Explain class and object with example (8 marks)


Class: Blueprint/ template that defines attributes (data) and methods (behavior). Object:
Instance of a class with real values. Example:

class Student: def __init__(self, name, roll): [Link] = name [Link] = roll def
display(self): return f"{[Link]} - {[Link]}" s = Student("Riya", 101) # object
print([Link]()) # Riya - 101

Note: Class defines __init__ (constructor); object stores state and can call methods.

4. What are user-defined exceptions? Steps to raise your own


exception (8 marks)
User-defined exception: Custom exception class created to represent application-specific
errors. Steps:

1. Define a class inheriting from Exception (or a subclass).


2. Use raise to raise it when condition fails.
3. Catch with except YourError: if needed. Example:

class AgeError(Exception): pass def check_age(a): if a < 18: raise AgeError("Age must be
18 or above") try: check_age(16) except AgeError as e: print("Caught:", e)

Use-case: clearer error messages and targeted exception handling.

5. Describe modules, use and controls in GUI program (8


marks)
Modules: Files containing Python code (functions/classes) which can be imported with
import. Modules promote code reuse and separation of concerns. Use in GUI: Separate
GUI layout, event handlers, and business logic into modules. Example modules: [Link],
[Link], [Link]. Controls (widgets) in GUI: Button, Label, Entry, Text, Frame, Listbox,
Radiobutton, Checkbutton, Menu. Example structure:

 [Link] → creates widgets and layout.


 [Link] → functions for button clicks.
 [Link] → imports ui and starts mainloop. Benefit: easier testing, maintainability,
teamwork.

6. Explain creating and populating tables in database with


SQL language (8 marks)
Create table:

CREATE TABLE Student ( id INT PRIMARY KEY, name VARCHAR(100), age INT,
grade VARCHAR(5) );

Insert rows:

INSERT INTO Student (id, name, age, grade) VALUES (1, 'Riya', 18, 'A'), (2, 'Aman', 19,
'B');

Select / Update / Delete examples:

SELECT * FROM Student WHERE age > 18; UPDATE Student SET grade = 'A+'
WHERE id = 2; DELETE FROM Student WHERE id = 1;
Notes: Use transactions (BEGIN, COMMIT, ROLLBACK) for safe multi-step updates.

7. What are joins? Explain inner join and left join with
example (8 marks)
Join: Combine rows from two or more tables using related columns.

 INNER JOIN: returns rows with matching keys in both tables.


 LEFT JOIN (LEFT OUTER): returns all rows from left table and matched rows
from right; unmatched right columns are NULL.

Example tables: students(id, name), marks(sid, score)

Inner join:

SELECT [Link], [Link], [Link] FROM students s INNER JOIN marks m ON [Link] = [Link];

Returns only students who have marks.

Left join:

SELECT [Link], [Link], [Link] FROM students s LEFT JOIN marks m ON [Link] = [Link];

Returns all students; score is NULL if no marks record exists.

8. What is exception handling and how to handle try, except


and finally statement (8 marks)
Exception handling: Mechanism to catch runtime errors and respond gracefully. Prevents
program crash and enables cleanup. Keywords: try, except, else, finally. Behavior:

 try block runs risky code.


 except handles specific exceptions.
 else runs if no exception occurred.
 finally always runs (used for cleanup: close files, release resources). Example:

try: f = open("[Link]") x = int([Link]()) print(10 / x) except FileNotFoundError:


print("File missing") except ZeroDivisionError: print("Division by zero") except
ValueError: print("Invalid number") else: print("No errors") finally: try: [Link]()
except: pass print("Cleanup done")
9. Explain assert statement (8 marks)
Definition: assert , checks a condition during development; if false, raises AssertionError
with message. Use: Debugging, verifying programmer assumptions, unit tests. Not to
replace runtime error handling (can be disabled with -O flag). Example:

def divide(a, b): assert b != 0, "b must not be zero" return a / b # divide(4, 0) ->
AssertionError: b must not be zero

Best practice: Use for internal checks, not user input validation in production.

10. Advanced features of database (8 marks)


Key advanced features:

1. Transactions & ACID (atomicity, consistency, isolation, durability)


2. Indexes (B-tree, hash) — speed up queries
3. Query optimizer / execution plans
4. Stored procedures & functions — server-side code
5. Triggers — automatic actions on data change
6. Views & Materialized Views — simplify queries / cache results
7. Replication (master-slave, master-master) — availability
8. Partitioning & Sharding — horizontal scaling for big data
9. MVCC / Concurrency control — consistent multi-user access
[Link] & recovery, encryption, auditing — safety & compliance

11. Method overloading, Generalization, Pure function —


Explain (1 mark each or 3 small parts) (8 marks total)
Method overloading: Defining same method name with different parameters. Python
doesn’t support it natively; emulate with default args or *args, **kwargs.

def add(a, b, c=0): return a+b+c

Generalization: Extract common attributes/behavior into a base class to reduce


duplication and allow reuse (see Vehicle → Car/Truck). Pure function: Function with no
side effects and deterministic output for same inputs (e.g., def add(a,b): return a+b).
12. Inheritance with program (8 marks)
Definition recap: Child reuses parent attributes/methods; supports overriding and
super(). Example covering single, multilevel and multiple inheritance:

class A: def f(self): return "A" class B(A): # single def f(self): return "B" class C(B): #
multilevel pass class X: def x(self): return "X" class Y: def y(self): return "Y" class Z(X,
Y): # multiple inheritance pass print(B().f(), C().f(), Z().x(), Z().y())

Note: Use super() in overriding methods to call parent implementation.

13. Discuss mutability, sameness, and copy of object in detail


with code example (8 marks)
Mutability: Whether an object’s content can change after creation.

 Mutable: list, dict, set (contents can change).


 Immutable: int, float, str, tuple (cannot change). Sameness:
 == checks value equality (depends on __eq__).
 is checks identity (same memory object). Copy of object:
 Shallow copy — copies top-level object, nested references shared.
 Deep copy — recursively copies nested objects.

Example:

import copy a = [1, [2,3]] b = [Link](a) # shallow c = [Link](a) # deep


a[1].append(4) print(a) # [1, [2,3,4]] print(b) # [1, [2,3,4]] <-- nested list shared (shallow)
print(c) # [1, [2,3]] <-- deep copy unaffected # sameness vs equality x = [1,2] y = [1,2]
print(x == y) # True (value) print(x is y) # False (different objects) z = x print(x is z) #
True (same object)

Implication: Use deepcopy when independent nested copies are required. Be careful with
mutable default args in functions.

14. Explain database keys and constraints: Primary Key,


Foreign Key, Unique constraint, NOT NULL constraint and
their importance (8 marks)
Primary Key (PK): Uniquely identifies each row; cannot be NULL. Ensures entity
integrity. Foreign Key (FK): Column referencing PK of another table; enforces referential
integrity (prevents orphan rows). Example: FOREIGN KEY (dept_id) REFERENCES
department(id). Unique constraint: Ensures column values are unique across rows (can be
NULL depending on DBMS). Use for columns like email. NOT NULL constraint:
Prevents NULL values; ensures attribute always has value. Importance: Together they
enforce data integrity, consistency, and support efficient indexing and joins. Useful for
preventing duplicate or invalid data and ensuring reliable relationships between tables.

Q1. Inheritance with Program (8–10 marks)


Definition:
Inheritance OOP ka mechanism hai jisme ek child class apne parent class ke attributes
aur methods ko reuse karti hai. Isse duplication kam hota hai aur code reusable ban jata
hai.

Types of Inheritance in Python:

1. Single Inheritance – one parent + one child


2. Multilevel Inheritance – parent → child → subchild
3. Multiple Inheritance – child inherits from multiple parents
4. Hierarchical – one parent, multiple children
5. Hybrid – combination of above types

Advantages:

 Code Reusability
 Less Redundancy
 Easy Extension
 Better Program Structure

Example Program:
class Animal:
def sound(self):
return "Some sound"

class Dog(Animal): # Single Inheritance


def sound(self):
return "Bark"

class Puppy(Dog): # Multilevel


pass

d = Dog()
p = Puppy()

print([Link]()) # Bark
print([Link]()) # Bark (inherited)

Q2. Basic Widgets in GUI (Tkinter) (8–10


marks)
Definition:
Tkinter Python ka built-in GUI package hai jisme widgets milte hain — ye GUI ke
building blocks hote hain.

Common Widgets:

 Label: Text/image display


 Entry: Single-line input
 Button: Click actions
 Text: Multiline text box
 Frame: Widget container
 Checkbutton: Boolean option
 Radiobutton: Multiple-choice option
 Listbox: List of selectable items

Example:
import tkinter as tk

root = [Link]()
[Link](root, text="Enter Name").pack()
e = [Link](root); [Link]()

[Link](root, text="Submit",
command=lambda: print([Link]())).pack()

[Link]()

Q3. Polymorphism (8–10 marks)


Definition:
Polymorphism = “many forms”. Same function/method alag objects ke liye alag output
deta hai.

Types:
 Method Overriding (Runtime polymorphism)
 Duck Typing (Python-specific flexibility)

Advantages:

 Flexible code
 Easy extension
 Clean & readable

Example:
class Cat:
def sound(self):
return "Meow"

class Cow:
def sound(self):
return "Moo"

def speak(animal):
print([Link]())

speak(Cat())
speak(Cow())

Q4. Generalization (8–10 marks)


Definition:
Generalization mein multiple classes ke common features ko ek parent class me shift kiya
jata hai.

Example Concept:
Car, Bus, Truck → Vehicle
Common: wheels, speed, start()

Example Code:
class Vehicle:
def __init__(self, wheels):
[Link] = wheels

def start(self):
return "Vehicle starting..."

class Car(Vehicle):
pass

c = Car(4)
print([Link]())
Q5. Pure Function (8–10 marks)
Definition:
Pure function ka output sirf inputs par depend karta hai, koi side-effect nahi hota.

Characteristics:

 Deterministic
 No external variable use
 No mutation
 Predictable & thread-safe

Example (Pure):
def add(a, b):
return a + b

Not Pure:
x = 10
def add_to_x(a):
return a + x

Q6. Method Overriding (8–10 marks)


Definition:
Child class apne parent class ke method ko overwrite karta hai → overriding.

Use:
Runtime polymorphism.

Example:
class Parent:
def display(self):
return "From Parent"

class Child(Parent):
def display(self):
return "From Child"

c = Child()
print([Link]())
Q7. Exception Handling + How to Handle (8–10
marks)
Definition:
Exception handling runtime errors ko safely catch karke program ko crash hone se
bachata hai.

Keywords:

 try – risky code


 except – error handling
 else – runs if no error
 finally – always runs

General Flow:

1. Error detect
2. Handle
3. Program continues

Example:
try:
x = int(input("Enter number: "))
print(10 / x)

except ZeroDivisionError:
print("Cannot divide by zero")

except ValueError:
print("Invalid input")

finally:
print("Execution complete")

Q8. try, except, finally (8–10 marks)


Meaning:

 try: possible error code


 except: error handling
 finally: always executes (cleanup)

Example:
try:
f = open("[Link]")
print([Link]())

except FileNotFoundError:
print("File missing")

finally:
print("This always executes")

Q9. Assert Statement (8–10 marks)


Definition:
assert debugging ke liye use hota hai. Condition false ho to AssertionError throw hota hai.

Uses:

 Input validation
 Debugging
 Testing assumptions

Example:
def square_root(x):
assert x >= 0, "x must be >= 0"
return x ** 0.5

print(square_root(9))
# square_root(-5) → AssertionError

Q10. Raising Custom Exception (8–10 marks)


Definition:
raise keyword se programmer apni custom error create kar sakta hai.

Example:
class AgeError(Exception):
pass

def check(age):
if age < 18:
raise AgeError("Age must be 18 or above")
return "Allowed"

print(check(20))
Q11. OOP in Python + Features (8–10 marks)
Definition:
OOP = Program designing using objects (data + methods).

Four Pillars:

1. Encapsulation
2. Abstraction
3. Inheritance
4. Polymorphism

Advantages:

 Real world modeling


 Reusability
 Less redundancy
 Maintainable code

Example:
class Student:
def __init__(self, name):
[Link] = name

def display(self):
return f"Student: {[Link]}"

print(Student("Riya").display())

Q12. Class and Object — Implementation (8–10


marks)
Class: Template for creating objects.
Object: Instance of class containing real data.

Features:

 Constructor
 Methods
 Attributes
 Encapsulation

Example:
class Student:
def __init__(self, name, roll):
[Link] = name
[Link] = roll

def info(self):
return f"{[Link]} - {[Link]}"

obj = Student("Riya", 101)


print([Link]())

Q13. Advanced Features of Database (8–10


marks)
Important Features:

1. ACID Transactions
2. Indexing for fast search
3. Stored Procedures
4. Triggers
5. Views / Materialized Views
6. Backup & Recovery
7. Replication
8. Sharding / Partitioning
9. Concurrency Control (locks, MVCC)
[Link]: roles, privileges, encryption

Why Important?

 Speed
 Reliability
 Scalability
 Data Protection

You might also like