Python Object Types and Programming Concepts
Python Object Types and Programming Concepts
a) Python objects
What is an Object?
An object in Python is an instance of a class, which is a blueprint for creating objects. Each
object has:
Python supports various built-in object types, which can be broadly categorized into:
1. Numeric Types:
o Integers: Whole numbers, e.g., 5, -10.
o Floats: Decimal numbers, e.g., 3.14, -0.001.
o Complex Numbers: Numbers with a real and imaginary part, e.g., 3 + 4j.
2. Sequence Types:
o Strings: Immutable sequences of characters, e.g., "hello", 'Python'.
o Lists: Mutable ordered collections, e.g., [1, 2, 3].
o Tuples: Immutable ordered collections, e.g., (1, 2, 3).
3. Mapping Type:
o Dictionaries: Unordered collections of key-value pairs, e.g., {'name':
'Alice', 'age': 30}.
4. Set Types:
o Sets: Unordered collections of unique elements, e.g., {1, 2, 3}.
o Frozensets: Immutable versions of sets.
5. Boolean Type:
o Represents True or False.
6. NoneType:
o Represents the absence of a value, indicated by the None keyword.
In Python, you can create custom objects by defining a class. Here’s a simple example:
class Dog:
def __init__(self, name, age):
[Link] = name # Attribute
[Link] = age # Attribute
def bark(self): # Method
return f"{[Link]} says Woof!"
1. Dynamic Typing:
o Python uses dynamic typing, meaning the type of an object is determined at
runtime, and variables can change types.
2. Mutability:
o Some objects (like lists and dictionaries) are mutable, meaning they can be
changed after creation. Others (like strings and tuples) are immutable.
3. Identity, Type, and Value:
o Every object has a unique identity (memory address), a type (defined by its class),
and a value (the data it holds).
4. Inheritance:
o Python supports inheritance, allowing new classes to inherit attributes and
methods from existing ones, promoting code reuse.
5. Polymorphism:
o Objects of different classes can be treated as objects of a common superclass. This
enables the same method to behave differently depending on the object’s class.
b) Lists
c) Exceptions
d) Packages
packages are a way to organize and distribute modules and related code. A package is essentially
a directory that contains multiple Python modules, and it may also include sub-packages. This
structure helps in maintaining and organizing large codebases, making it easier to manage
dependencies and namespace collisions.
1. Package Structure:
o A package is a directory that contains an __init__.py file (which can be empty).
This file indicates to Python that the directory should be treated as a package.
o Packages can contain sub-packages and modules, allowing for a hierarchical
organization of code.
Example Structure:
my_package/
__init__.py
[Link]
[Link]
sub_package/
__init__.py
[Link]
Example:
my_package/
__init__.py
math_operations.py
string_operations.py
3. Using Packages: You can import modules from a package using the import statement.
Example:
Example:
my_package/
__init__.py
utilities/
__init__.py
file_utils.py
network_utils.py
Organization: Packages help organize related modules into a coherent structure, making
it easier to navigate and maintain the codebase.
Namespace Management: Packages prevent name conflicts by encapsulating modules
in their own namespaces.
Reusability: Modules within packages can be reused across different projects, promoting
code reuse.
Dependency Management: When distributing packages, dependencies can be managed
more effectively, ensuring that all required modules are available.
e) Regular expressions
Regular expressions (regex) in Python are powerful tools for searching, matching, and
manipulating strings based on specific patterns. The re module in Python provides functions to
work with regex. Here’s a quick overview of how to use them:
Basic Functions
import re
4. Replacing Patterns
o [Link](): Replaces occurrences of a pattern with a specified string.
result = [Link](r'apples', 'bananas', 'There are 123 apples')
print(result) # Output: There are 123 bananas
5. Splitting Strings
o [Link](): Splits a string by the occurrences of a pattern.
Common Patterns
Example Usage
import re
f) Thread module
The thread module in Python provides low-level primitives for working with threads. However,
it has been largely superseded by the threading module, which offers a higher-level interface
and more features.
Key Features of the threading Module
1. Thread Creation: You can create new threads by subclassing Thread or by using the
Thread class directly.
2. Thread Synchronization: It includes locks, conditions, and semaphores to help manage
thread interactions and prevent race conditions.
3. Daemon Threads: You can create threads that run in the background and terminate when
the main program exits.
4. Thread Communication: You can use queues to facilitate communication between
threads.
import threading
import time
def worker():
print("Worker thread is running")
[Link](2)
print("Worker thread is done")
# Create a thread
thread = [Link](target=worker)
g) Web surfing
Web surfing in Python typically involves using libraries to interact with web pages, scrape
content, or automate browsing tasks. Here are some popular libraries and methods for web
surfing in Python:
1. Requests
The requests library is great for making HTTP requests to retrieve web content.
import requests
response = [Link]('[Link]
print([Link])
2. Beautiful Soup
For parsing HTML and extracting data, Beautiful Soup works well in conjunction with
requests.
response = [Link]('[Link]
soup = BeautifulSoup([Link], '[Link]')
3. Selenium
If you need to interact with web pages (like clicking buttons or filling out forms), Selenium can
control a web browser.
# Set up the web driver (make sure you have the appropriate driver installed)
driver = [Link]()
[Link]('[Link]
4. Scrapy
For more complex web scraping tasks, Scrapy is a powerful framework that allows you to define
spiders to crawl websites and extract structured data.
# Install Scrapy
pip install scrapy
You would create a new Scrapy project and define your spiders to crawl and scrape data.
5. Pyppeteer
For headless browsing (running a browser without a GUI), Pyppeteer is a good choice. It's a
Python port of Puppeteer, which is a [Link] library.
import asyncio
from pyppeteer import launch
asyncio.get_event_loop().run_until_complete(main())
Considerations
Respect [Link]: Always check a website's [Link] file to ensure that your
scraping activities are allowed.
Rate Limiting: Be mindful of how frequently you make requests to avoid overwhelming
the server.
Legal Compliance: Ensure that your activities comply with the website's terms of
service.
h) Web servers
Creating web servers in Python can be done using various frameworks and libraries, each suited
for different use cases. Here are some popular options:
1. Flask
Flask is a lightweight and easy-to-use micro web framework for building web applications.
app = Flask(__name__)
@[Link]('/')
def hello():
return "Hello, World!"
if __name__ == '__main__':
[Link](debug=True)
2. Django
# Install Django
pip install django
3. FastAPI
FastAPI is a modern framework for building APIs with Python 3.6+ based on standard Python
type hints, which makes it fast and easy to use.
app = FastAPI()
@[Link]("/")
def read_root():
return {"Hello": "World"}
4. Tornado
Tornado is an asynchronous networking library and web framework, great for handling long-
lived connections and WebSockets.
class MainHandler([Link]):
def get(self):
[Link]("Hello, World!")
app = [Link]([
(r"/", MainHandler),
])
if __name__ == "__main__":
[Link](8888)
[Link]().start()
5. [Link]
For simple use cases or development purposes, Python's built-in [Link] module can be
used to create a basic HTTP server.
PORT = 8000
class MyHandler(SimpleHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.end_headers()
[Link](b"Hello, World!")
If you have a specific use case or need help with a particular framework, let me know!
i) DB-API
The Python Database API (DB-API) is a specification for a standard interface that Python
programs can use to interact with databases. It is defined in PEP 249 and provides a consistent
way to connect to different database systems, execute SQL queries, and manage results.
Basic Example:
import sqlite3
# Create a table
[Link]('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY,
name TEXT)')
# Print users
print(users)
This specification allows for greater flexibility and portability of database code across different
database systems in Python.
j) CGI.
Common Gateway Interface (CGI) is a standard protocol used to enable web servers to interact
with executable programs, typically scripts, to generate dynamic web content. In Python, CGI
allows you to create web applications that can respond to user requests by generating HTML or
other content dynamically.
1. Execution Environment: When a web server receives a request for a CGI script, it
executes the script in a specific environment and sends the output back to the client.
2. HTTP Request and Response: CGI scripts process input from the user (like form data)
and return a response to the web browser.
3. Standard Input and Output: CGI scripts read from standard input (usually the request
data) and write to standard output (the HTTP response).
4. Content-Type Header: The first line of the output must specify the content type (e.g.,
Content-Type: text/html), followed by a blank line.
#!/usr/bin/env python3
import cgi
# Output HTML
print("<html>")
print("<head><title>CGI Example</title></head>")
print("<body>")
print("<h1>Hello, CGI!</h1>")
print("<p>This is a simple CGI script written in Python.</p>")
print("</body>")
print("</html>")
CGI scripts are executed for each request, which may lead to performance issues for
high-traffic sites.
Alternatives like WSGI or web frameworks (Flask, Django) are often preferred for more
complex applications.
Always sanitize user input to prevent security vulnerabilities.
CGI provides a straightforward way to create dynamic web content in Python, although it is less
common in modern web development.
SECTION-B
2. List any five built-in functions used in Python. Give suitable examples.
en()
Description: Returns the length (number of items) of an object (e.g., string, list, tuple).
Example:
my_list = [1, 2, 3, 4, 5]
print(len(my_list)) # Output: 5
2. type()
Example:
num = 10
print(type(num)) # Output: <class 'int'>
text = "Hello"
print(type(text)) # Output: <class 'str'>
3. max()
Description: Returns the largest item in an iterable or the largest of two or more arguments.
Example:
4. sum()
Example:
numbers = [1, 2, 3, 4, 5]
print(sum(numbers)) # Output: 15
5. sorted()
Description: Returns a new sorted list from the elements of any iterable.
Example:
numbers = [5, 2, 9, 1, 5, 6]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 2, 5, 5, 6, 9]
These built-in functions are fundamental to Python programming and provide essential
functionality for manipulating data and objects.
Namespaces in Python are crucial for managing the scope and visibility of variables, functions,
and objects within a program. They serve several significant purposes:
1. Organizing Code
Namespaces help organize and structure code, allowing for better management of variables and
functions. This organization helps avoid naming conflicts, especially in larger projects or when
using multiple modules.
By providing a unique context for variable names, namespaces prevent name collisions. For
example, you can have a function and a variable with the same name in different namespaces
without conflict.
3. Scope Management
Namespaces define the scope in which variables and functions are accessible. This scope can be
global (accessible throughout the program), local (accessible only within a function), or built-in
(names provided by Python).
4. Modularity
5. Dynamic Binding
Python uses namespaces to support dynamic binding. This means that names can be assigned to
different objects at runtime, enabling more flexible programming.
Types of Namespaces
1. Built-in Namespace: Contains names built into Python (e.g., print, len).
2. Global Namespace: Contains names defined at the top level of a module or script.
3. Local Namespace: Contains names defined within a function. Each function call creates
a new local namespace.
4. Enclosing Namespace: Exists in nested functions, containing names from the outer
function's scope.
Example
x = "global"
def outer_function():
x = "outer"
def inner_function():
x = "inner"
print("Inner:", x) # Refers to the inner function's x
inner_function()
print("Outer:", x) # Refers to the outer function's x
outer_function()
print("Global:", x) # Refers to the global x
Output:
sql
Copy code
Inner: inner
Outer: outer
Global: global
In this example:
The inner_function has access to its local x, the outer_function's x, and the global x,
demonstrating how namespaces control variable access.
5. Write a python program to calculate the length of a string without using library
functions.
Python program to calculate the length of a string without using any library functions:
def string_length(input_string):
count = 0 # Initialize a counter
for char in input_string: # Iterate over each character in the string
count += 1 # Increment the counter for each character
return count # Return the final count
# Example usage
user_input = input("Enter a string: ")
length = string_length(user_input)
print("The length of the string is:", length)
Explanation:
You can run this program, enter a string, and it will display the length of that string.
5. Write the steps to create simple web clients in Python.
6. Creating a simple web client in Python can be accomplished using various libraries, with
the most common being requests. Below are the steps to create a simple web client that
can make HTTP requests and handle responses.
7. Steps to Create a Simple Web Client in Python
8. Step 1: Install the Requests Library
9. If you haven't installed the requests library yet, you can do so using pip. Open your
terminal or command prompt and run:
10. pip install requests
SECTION-C
6. How multi-threaded programming is done in Python? Give an illustration.
1. Import the threading Module: This module provides the necessary classes and
functions for creating threads.
2. Define a Function for the Thread: Create a function that you want the thread to
execute.
3. Create Thread Objects: Instantiate Thread objects, passing the target function and any
arguments it requires.
4. Start the Threads: Use the start() method to begin the execution of each thread.
5. Wait for Threads to Complete: Optionally, use the join() method to ensure the main
program waits for the threads to finish.
Example
import threading
import time
def print_letters():
for letter in 'abcde':
print(f"Letter: {letter}")
[Link](1) # Simulating a delay
Output
When you run the program, the output will interleave the numbers and letters, demonstrating that
both functions are running concurrently:
Number: 1
Letter: a
Number: 2
Letter: b
Number: 3
Letter: c
Number: 4
Letter: d
Number: 5
Letter: e
Both threads have finished execution.
Important Notes
Global Interpreter Lock (GIL): Python's GIL means that only one thread can execute
Python bytecode at a time. This can limit the effectiveness of threading for CPU-bound
tasks. However, it works well for I/O-bound tasks.
Thread Safety: Be cautious with shared data between threads. Use synchronization
mechanisms like Lock if necessary to avoid race conditions.
7. Define lists in Python. Write a python program to find the intersection of two lists.
Lists in Python
Lists in Python are ordered, mutable collections of items that can hold a variety of data types,
including numbers, strings, and other objects. Lists are defined using square brackets [], and
items are separated by commas. They allow duplicate elements and can be modified after
creation.
Ordered: The items have a defined order, and that order will not change unless explicitly
modified.
Mutable: You can change, add, or remove items after the list has been created.
Dynamic: Lists can grow and shrink in size as needed.
The intersection of two lists is a new list that contains only the elements that are present in both
lists. Here's a Python program to find the intersection of two lists:
# Example usage
list_a = [1, 2, 3, 4, 5]
list_b = [4, 5, 6, 7, 8]
Output
8. Discuss the commonly used Tkinter widgets used with python programming.
Tkinter is the standard GUI (Graphical User Interface) toolkit for Python, providing a range of
widgets to create interactive applications. Here are some commonly used Tkinter widgets:
1. Label
2. Button
3. Entry
entry = [Link](root)
[Link]()
4. Text
5. Checkbutton
var = [Link]()
checkbutton = [Link](root, text="Option 1", variable=var)
[Link]()
6. Radiobutton
Description: A button that allows users to select one option from a set.
Usage: Used when only one choice is allowed from multiple options.
var = [Link]()
radiobutton1 = [Link](root, text="Option A", variable=var, value="A")
radiobutton2 = [Link](root, text="Option B", variable=var, value="B")
[Link]()
[Link]()
7. Listbox
Description: Displays a list of items from which users can select one or more.
Usage: Used for selections from a predefined list.
listbox = [Link](root)
[Link](1, "Item 1")
[Link](2, "Item 2")
[Link]()
8. Menu
menu = [Link](root)
[Link](menu=menu)
file_menu = [Link](menu)
menu.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="Open", command=open_file)
9. Frame
10. Canvas