0% found this document useful (0 votes)
19 views6 pages

Python Modules and OOP Basics

This document covers Python programming concepts including modules, random numbers, time and math modules, and creating custom modules. It also explains mutable vs immutable types, aliasing, and object-oriented programming principles such as classes, attributes, and methods. The document provides example programs to illustrate each concept.

Uploaded by

vikasm0427
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)
19 views6 pages

Python Modules and OOP Basics

This document covers Python programming concepts including modules, random numbers, time and math modules, and creating custom modules. It also explains mutable vs immutable types, aliasing, and object-oriented programming principles such as classes, attributes, and methods. The document provides example programs to illustrate each concept.

Uploaded by

vikasm0427
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

1BPLC105B - Python Programming

MODULE -4
Modules: Random numbers, the time module, the math module, creating your own modules,
Namespaces, Scope and lookup rules, Attributes and the dot Operator, Three import statement
variants.

Mutable versus immutable and aliasing

Object oriented programming: Classes and Objects — The Basics, Attributes, Adding methods
to our class, Instances as arguments and parameters, Converting an instance to a string,
Instances as return values.

1. Modules
A module is a file containing Python code such as functions, variables, and classes. Modules help
in organizing code logically and enable reusability. Python comes with many built-in modules
like math, time, and random. We can also create our own modules.

1.1 Random Numbers


The random module is used to generate pseudo-random numbers for various purposes such as
games, simulations, and testing.

Example Program:

import random

print([Link]()) # Random float [0.0, 1.0)


print([Link](1, 10)) # Random int between 1 and 10
print([Link](['A', 'B', 'C'])) # Random choice from list

items = [1, 2, 3, 4]
[Link](items) # Shuffle list
print(items)

1.2 The time Module


The time module provides functions to work with time. It can be used to measure execution
time, pause program execution, and display current time.

Example Program:

import time

print("Current time (epoch):", [Link]())


print("Readable format:", [Link]())

print("Sleeping for 2 seconds...")

1|Page
1BPLC105B - Python Programming

[Link](2)
print("Awake now!")

1.3 The math Module


The math module provides mathematical constants and functions like square root,
trigonometric functions, logarithms, and more.

Example Program:

import math

print("Pi:", [Link])
print("Square root of 16:", [Link](16))
print("2 raised to power 3:", [Link](2, 3))
print("Factorial of 5:", [Link](5))
print("Log base e of 10:", [Link](10))
print("Sine 90 degrees:", [Link]([Link](90)))

1.4 Creating Your Own Modules


You can create your own module by saving Python functions in a .py file and importing it into
another program.

Example Program:

# [Link]
def greet(name):
return f"Hello, {name}!"

def add(a, b):


return a + b

# [Link]
import mymodule
print([Link]("Alice"))
print([Link](5, 3))

1.5 Namespaces and Scope


A namespace is a mapping between names and objects. Scope refers to the region where a
variable is accessible. Python follows the LEGB rule (Local, Enclosing, Global, Built-in).

Example Program:

x = "global"

def outer():
x = "enclosing"
def inner():

2|Page
1BPLC105B - Python Programming

x = "local"
print("Inside inner:", x)
inner()
print("Inside outer:", x)

outer()
print("Outside:", x)

1.6 Attributes and Dot Operator


Attributes are variables/functions associated with objects. They are accessed using the dot (.)
operator.

Example Program:

import math
print([Link])
print([Link](25))

1.7 Import Variants


Python supports different ways to import modules and functions:
1. import module
2. from module import name
3. import module as alias

Example Program:

import math
print([Link](16))

from math import sqrt


print(sqrt(16))

import math as m
print([Link](16))

2. Mutable vs Immutable & Aliasing

2.1 Mutable and Immutable


Mutable objects can be changed after creation (e.g., list, dict), while immutable objects cannot
(e.g., int, str, tuple).

Example Program:

# Immutable
a = "Hello"
b=a

3|Page
1BPLC105B - Python Programming

b = b + " World"
print(a) # Hello

# Mutable
x = [1, 2, 3]
y=x
[Link](4)
print(x) # [1, 2, 3, 4]

2.2 Aliasing
Aliasing occurs when two variables refer to the same object in memory.

Example Program:

list1 = [10, 20]


list2 = list1
[Link](30)
print(list1) # [10, 20, 30]

3. Object-Oriented Programming (OOP)

3.1 Classes and Objects


A class is a blueprint for creating objects. An object is an instance of a class.

Example Program:

class Dog:
def bark(self):
print("Woof!")

d = Dog()
[Link]()

3.2 Attributes
Attributes are variables that belong to a class or instance.

Example Program:

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

dog1 = Dog("Tommy")
print([Link])

4|Page
1BPLC105B - Python Programming

3.3 Adding Methods


Methods are functions defined inside a class that operate on attributes.

Example Program:

class Dog:
def __init__(self, name):
[Link] = name
def bark(self):
print(f"{[Link]} says Woof!")

dog1 = Dog("Rocky")
[Link]()

3.4 Instances as Arguments


Objects can be passed as arguments to methods.

Example Program:

class Dog:
def __init__(self, name):
[Link] = name
def play_with(self, other):
print(f"{[Link]} plays with {[Link]}")

dog1 = Dog("Max")
dog2 = Dog("Buddy")
dog1.play_with(dog2)

3.5 Converting to String


The __str__ method allows you to define a string representation of an object.

Example Program:

class Dog:
def __init__(self, name):
[Link] = name
def __str__(self):
return f"Dog named {[Link]}"

dog1 = Dog("Leo")
print(dog1)

3.6 Instances as Return Values


A method can return a new object instance.

Example Program:

5|Page
1BPLC105B - Python Programming

class Dog:
def __init__(self, name):
[Link] = name
def clone(self):
return Dog([Link])

dog1 = Dog("Ruby")
dog2 = [Link]()
print([Link])

6|Page

Common questions

Powered by AI

Mutable objects, such as lists or dictionaries, can be changed after their creation. For example, appending a new element to a list will modify it in-place . In contrast, immutable objects like strings and tuples maintain constant values, necessitating the creation of a new object to reflect changes . Aliasing occurs when two variables reference the same object in memory, causing changes to be reflected across all references, as demonstrated with lists where appending to one alias affects the original list .

To create a custom module in Python, save your functions in a .py file, such as `mymodule.py`, and import it into other programs using an import statement, like `import mymodule`. This approach allows for the logical organization of code, improving its readability and reusability across projects . For instance, a custom module could contain utility functions for a consistent, uniform use within various scripts, enhancing maintainability and reducing redundancy by centralizing code functionality in one location .

Python supports three import statement variants: (1) import module, which imports the entire module and requires you to prefix functions with the module name; (2) from module import name, which imports specific items and allows you to use them without a module prefix; (3) import module as alias, which imports the module under an alias, enabling you to use a shorter name for module functions .

Namespaces map names to objects in Python, determining the scope where variables are accessible. The LEGB rule applies to the variable lookup process by searching for a variable in the Local, Enclosing, Global, and Built-in scopes sequentially. If a name is found at any level, the search stops, utilizing that object . This hierarchy organizes variable resolution within different contexts of a program, preventing conflicts between identically named variables and facilitating modular code organization .

Instances in Python can be passed as arguments to methods, allowing for interactions between objects. For example, the play_with method in a Dog class can take another Dog instance as an argument, facilitating behaviors involving multiple objects . Additionally, a method can return a new instance, enabling object manipulation and duplication, such as a clone method creating a copy of a Dog object . This approach leverages encapsulation and abstraction, enhancing modularity and reuse by maintaining contextual method operations across instances .

Object-oriented programming (OOP) in Python encourages code reuse and modularity through classes and objects. Classes define blueprints for objects, encapsulating data and behavior, which can be reused across different parts of a program. Key concepts supporting OOP include inheritance, where new classes derive attributes and methods from existing ones, and polymorphism, which allows for methods to function differently based on the object context. Encapsulation improves modularity by hiding internal details and exposing only necessary interfaces . For example, methods like __str__ provide custom object representations, facilitating integration with other components .

In Python, mutable objects allow in-place modifications, impacting memory management by maintaining a single object instance despite changes, as seen when modifying a list through aliasing, where multiple references point to the same memory location . For example, modifying list1 by adding an element will reflect in list2 if it is an alias, preserving memory by avoiding duplication . Immutable objects require creating entirely new instances for modifications, leading to higher memory usage for string concatenations, for example. This distinction influences how variables are stored and referenced, making aliasing a crucial concept for efficient memory usage and avoiding unintended side effects .

Python treats certain data types as mutable or immutable based on their intended usage and the need for predictable behavior. Immutable types (e.g., ints, strings, tuples) offer advantages in data integrity and hashability, assisting with consistent and safe operations, especially in concurrent programming or when using keys in dictionaries. In contrast, mutable types (e.g., lists, dictionaries) allow in-place modifications, which are essential for efficiency in dynamic algorithms that frequently alter data. The implications in program design involve choosing the appropriate data type according to desired behavior; immutables provide safety and simplicity, while mutables allow flexibility and efficiency .

The document introduces several Python standard modules: the 'random' module for generating pseudo-random numbers helpful in simulations and games; the 'time' module for working with time-related functions, such as measuring execution time and pausing execution; and the 'math' module providing mathematical functions and constants, like square root, power, and trigonometric functions . For instance, the random module's `randint` function can generate a random integer within a specified range, while `math.pi` provides the value of π for calculations involving circles .

In object-oriented programming, attributes are variables defined within a class that represent the state or properties of objects. They are used within a class by initializing them in methods like __init__, allowing different instances of the class to maintain individual states. For example, a Dog class may have a name attribute set during object instantiation to personalize behavior across different Dog instances . Attributes are accessed and modified using the dot operator, permitting management of an object's state throughout its lifecycle .

You might also like