Akhila Py
Akhila Py
9Q:label,menu,message box
You can create your own modules by saving Python code in a `.py` file. Here’s a
simple example:
**Creating a Module:**
Create a file named `my_module.py`:
```python
# my_module.py
def greet(name):
return f"Hello, {name}!"
def add(a, b):
return a + b
Using Your Module:
You can then import and use your module in another Python file:
python
import my_module
print(my_module.greet("Alice")) # Output: Hello, Alice!
print(my_module.add(3, 4)) # Output: 7
def speak(self):
return "Some generic sound"
class Dog(Animal):
def speak(self):
return "Bark"
Types of Inheritance:
1. Single Inheritance: A subclass inherits from one superclass.
2. Multiple Inheritance: A subclass inherits from more than one superclass.
3. Multilevel Inheritance: A subclass inherits from another subclass.
4. Hierarchical Inheritance: Multiple subclasses inherit from a single
superclass.
5. Hybrid Inheritance: A combination of two or more types of inheritance.
Benefits of Inheritance:
1. Reusability: Code written in the superclass can be reused in subclasses,
reducing redundancy.
2. Extensibility: New functionality can be added to existing classes without
modifying them.
3. Maintenance: Easier to update and maintain code as changes in the
superclass are reflected in all subclasses.
4. Organization: Provides a clear structure, making the code more
understandable and logical.
LONG
3Q: Multithreading
Multithreaded programming in Python can be effectively managed using the
`threading` module. Below is a breakdown of key concepts, including creating
threads, synchronizing them, and implementing a multithreaded priority queue.
1. Creating a Thread
You can create threads using either the `Thread` class from the `threading`
module
or by subclassing it. Here’s a simple example of both methods:
Using Thread class directly:
python
import threading
import time
def worker():
print("Thread is starting...")
time.sleep(2)
print("Thread has finished.")
# Creating a thread
thread = threading.Thread(target=worker)
thread.start()
# Wait for the thread to finish
thread.join()
print("Main thread continues...")
Subclassing Thread
python
import threading
import time
class MyThread(threading.Thread):
def run(self):
print("Thread is starting...")
time.sleep(2)
print("Thread has finished.")
# Creating a thread
thread = MyThread()
thread.start()
thread.join()
print("Main thread continues...")
2. Synchronizing Threads
Synchronization is crucial when multiple threads access shared resources. You
can
use locks to ensure that only one thread accesses a resource at a time.
**Using Lock:**
```python
import threading
lock = threading.Lock()
shared_resource = 0
def increment():
global shared_resource
for _ in range(100000):
with lock:
shared_resource += 1
threads = []
for _ in range(2):
thread = threading.Thread(target=increment)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
print(f"Final value of shared resource: {shared_resource}")
3. Multithreaded Priority Queue
For managing tasks that need to be processed based on priority, you can use
`queue.PriorityQueue`. This allows you to assign a priority to each task.
Example of a multithreaded priority queue:
python
import threading
import queue
import time
# Define a worker that processes tasks
def worker(priority_queue):
while True:
try:
priority, task = priority_queue.get(timeout=1) # Timeout to prevent
blocking
print(f"Processing task: {task} with priority: {priority}")
time.sleep(1) # Simulate work
priority_queue.task_done()
except queue.Empty:
break
# Create a priority queue
priority_queue = queue.PriorityQueue()
# Adding tasks to the queue (priority, task)
tasks = [(2, "Task 2"), (1, "Task 1"), (3, "Task 3")]
for task in tasks:
priority_queue.put(task)
# Creating multiple threads to process the queue
threads = []
for _ in range(3):
thread = threading.Thread(target=worker, args=(priority_queue,))
threads.append(thread)
thread.start()
# Wait for all threads to finish
for thread in threads:
thread.join()
print("All tasks completed.")