Dr. SURESHA V
A Simplified Notes As per VTU Syllabus
2025 Scheme
PYTHON PROGRAMMING
Code: 1BPLCK105B/205B
Professor & Principal
Dept. of E&CE
K.V.G. College of Engineering, Sullia, D.K-574 327
Affiliated to Visvesvaraya Technological University
Belagavi - 590018
MODULE 4
Modules | Mutable versus Immutable & Aliasing
Object-Oriented Programming (OOP)
Strings, Tuples and Lists
Python Programming(1BPLCK105B) - Module 4: Modules | Mutable versus Immutable & Aliasing
Object-Oriented Programming(OOP)
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 1
MODULE 4
Modules | Mutable versus Immutable & Aliasing
Object-Oriented Programming(OOP)
Syllabus:
▪ 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.
Chapter: 8.1-8.8, 9.1, 11.1
Text Book: Peter Wentworth, Jeffrey Elkner, Allen B. Downey and Chris
Meyers- How to think like a computer scientist: learning with python 3. Green
Tea Press, Wellesley, Massachusetts,2020
Chapter 8: MODULES
8.1 Introduction
o A module is a single Python file with a .py extension that serves as an
organisational unit of code.
o It can define functions, classes, variables, and executable statements
that can then be imported and used in other Python programs.
o The following modules are learn in this section are
1. The random numbers Module
2. The time Module
3. The math Module
8.2 The random numbers Module
o Python has a built-in module that you can use to make random
numbers.
o It is a built-in library that provides functions for generating pseudo-
random numbers and performing random operations.
o It introduces randomness into programs.
Python Programming(1BPLCK105B) - Module 4: Modules | Mutable versus Immutable & Aliasing
Object-Oriented Programming(OOP)
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 2
▪ Random numbers: A few typical uses are
1. To play a game of chance where the computer needs to throw some
dice, pick a number, or flip a coin.
2. To shuffle a deck of playing cards randomly.
3. To allow/make an enemy spaceship appear at a random location and
start shooting at the player.
4. To simulate possible rainfall when we make a computerised model for
estimating the environmental impact of building a dam.
5. For encrypting banking sessions on the Internet.
▪ random module: ***
o It is a built-in library used for generating pseudo-random numbers for
various non-security-related applications like simulations, games, and
testing.
o It provides functions for generating random integers, floats, and
making random selections from sequences.
o The random module has a set of methods shown below
Method Description
random() Returns a random float number between 0 and 1
randint() Returns a random number between the given range
randrange() Returns a random number between the given range
seed() Initialise the random number generator
shuffle() Takes a sequence and returns the sequence in a random order
sample() Returns a given sample of a sequence
uniform() Returns a random float number between two given parameters
choice() Returns a random element from the given sequence
▪ Examples of Random Module: import the random module in a program
1. random() method:
o It is a built-in method in a random module.
o It generates a random float number between 0.0 and 1.0
o Examples:
Program Output
Python Programming(1BPLCK105B) - Module 4: Modules | Mutable versus Immutable & Aliasing
Object-Oriented Programming(OOP)
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 3
2. randrange() Method:
o It is a built-in method in a random module.
o It generates a random number between the given range
o Syntax: random.randrange(start, end,step)
o Examples:
Program Output
7
2
93
21
3. shuffle() Method:
o It is a built-in method in a random module.
o Takes a sequence and returns the sequence in a random order.
o Example:
Program Output
['apple','cherry', 'banana']
[17, 35, 46, 4, 40, 23, 20, 29,
33, 36, 38, 48, 2, 12, 51, 18,
21, 9, 1, 6, 7, 45, 22, 43, 15,
24, 8, 11, 50, 25, 32, 13, 49,
41, 39, 19, 44, 31, 3, 42, 27,
30, 10, 5, 14, 28, 34, 26, 47,
0, 16, 37]
4. shuffle() Method:
o Takes a sequence and returns the sequence in a random order. Example
Program Output
M
(run the code for the first time)
Python Programming(1BPLCK105B) - Module 4: Modules | Mutable versus Immutable & Aliasing
Object-Oriented Programming(OOP)
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 4
L
(run the same code a second
time)
88
(run the code for the first time)
71
(run the same code a second
time)
8.2.1 Repeatability and Testing
o Repeatability:Ability to produce the same sequence of numbers multiple times.
o Random number generators are based on a deterministic algorithm — repeatable
and predictable. So they’re called pseudo-random generators — they are not
genuinely random.
o They start with a seed value. Each time you ask for another random number,
you’ll get one based on the current seed attribute, and the state of the seed
(which is one of the attributes of the generator) will be updated.
▪ seed() Method:
o The seed() method is used to initialise the random number generator.
o It creates a random number generator and gives an explicit seed value to object.
o The random number generator requires a starting value (a seed) to generate a
random number. Without this argument, the system probably uses something
based on the time. Example: Program to generate a random number with a seed
o
Python Programming(1BPLCK105B) - Module 4: Modules | Mutable versus Immutable & Aliasing
Object-Oriented Programming(OOP)
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 5
o Output will be identical for both "First run" and "Second run" sections.
8.1.2 Picking balls from bags, throwing dice, shuffling a pack of cards
o Random module may be used to generate random numbers, print a random value
from a list or string, and so on in the above applications
o Here is an example to generate a list containing n random integers between a lower
and an upper bound.
Program:
Output: 1 First Run Output: 2 Second Run
o After running the same program, we generated five random numbers, and
every run produced different results. But notice that we got a duplicate in
the result. Often, this is wanted, for example, when we throw a die five
times, we would expect some duplicates.
o Suppose we wanted five numbers between one and ten million, without
duplicates. Generating a list of ten million items
Python Programming(1BPLCK105B) - Module 4: Modules | Mutable versus Immutable & Aliasing
Object-Oriented Programming(OOP)
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 6
Program:
Output: 1 First Run
Output: 2 Second Run
8.2 The time module
o The time module provides functions for working with time values and
delays.
o Use it to measure
1. elapsed time
2. add delays
3. format timestamps, or convert between time representations.
o The time module in Python provides various functions for working with
time, including measuring time intervals, pausing program
execution, and formatting time representations.
o The time module has a function called clock that is recommended for
measuring the processor, the current time,sleep time, and elapsed time.
Python Programming(1BPLCK105B) - Module 4: Modules | Mutable versus Immutable & Aliasing
Object-Oriented Programming(OOP)
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 7
o Whenever the clock is called, it returns a floating-point number
representing how many seconds have elapsed since your program
started running.
o Example: Get the current time and sleep for 5 seconds
Program Output
Start time:
1767088974.210592
Elapsed: 5.00 seconds
▪ time.clock() method was used for measuring processor time or elapsed
time, depending on the operating system. time.clock() method of the time
module in Python is used to get the current processor time as a floating point
number expressed in seconds.
▪ Write a Python code to measure the program execution time of a given
processor to sum the elements in a list, which has a million elements...
Ans: Consider a variable t0 to be the start time and t1 to be the end time. The
difference t1-t0 is the time elapsed, and is a measure of how fast your program is
running.
Python Programming(1BPLCK105B) - Module 4: Modules | Mutable versus Immutable & Aliasing
Object-Oriented Programming(OOP)
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 8
o Program:
o Output:
o So our function runs about 57% slower than the built-in one. Generating and
summing up ten million elements in under a second.
8.3 The math module
o Python has a built-in module that you can use for mathematical tasks.
o This module contains the kinds of mathematical functions like sin, cos, sqrt, log,
log10 and some mathematical constants like pi and e:
o Examples
>>> import math
>>> math.pi # Constant pi
3.141592653589793
>>> math.e # Constant natural log base
2.718281828459045
Python Programming(1BPLCK105B) - Module 4: Modules | Mutable versus Immutable & Aliasing
Object-Oriented Programming(OOP)
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 9
>>> math.sqrt(2.0) # Square root function
1.4142135623730951
>>> math.radians(90) # Convert 90 degrees to radians
1.5707963267948966
>>> math.sin(math.radians(90)) # Find sin of 90 degrees
1.0
>>> math.asin(1.0) * 2 # Double the arcsin of 1.0 to get pi
3.141592653589793
o There are two functions radians and degrees to convert between these two popular
ways of measuring angles.
o Mathematical functions are “pure” and don’t have any state — calculating the
square root of 2.0 doesn’t depend on any kind of state or history about what
happened in the past.
o So the functions are not methods of an object—they are simply functions that are
grouped in a module called math.
8.4 Creating your own modules
o Creating your own modules in Python involves saving Python code in a file with
a .py extension. This file then acts as a reusable library that can be imported and used
in other Python scripts. Create a new file with a .py extension.
o For example, my_module.py. Define functions, classes, or variables. Inside this file,
define the functions, classes, or variables that you want to make available for use in
other scripts.Suppose,for example, this script is saved as a file named mymodule.py
Python Programming(1BPLCK105B) - Module 4: Modules | Mutable versus Immutable & Aliasing
Object-Oriented Programming(OOP)
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 10
o Now we can use our module, both in scripts we write and in the interactive Python
interpreter. To do so, we must first import the module name mymodule in the scripts.
o The use of modules makes it possible to break up very large programs into
manageable-sized parts, and to keep related parts together.
8.5 Namespaces
o A namespace is a collection of identifiers that belong to a module, or to a function.
o A Namespace in Python is a container that holds a set of identifiers (variable names)
and their associated objects (values).
o To put it simply, a namespace is a collection of names.
o A Python namespace is a mapping from names to objects.
o Each module has its own namespace, so we can use the same identifier name in
multiple modules without causing an identification problem.
o This allows us to use the same name for different variables or objects in different parts
of our code, without causing any conflicts or confusion.
o Let's consider two separate modules that are created with a module name, module1.py
and module2.py
# module1.py
>>> question = "What is the meaning of Life, the Universe, and Everything?"
>>> answer = 42
# module2.py
>>> question = "What is your quest?"
>>> answer = "To seek the holy grail."
o We can now import both modules and access questions and answers in each:
>>> import module1
>>> import module2
>>> print(module1.question)
>>> print(module2.question)
>>> print(module1.answer)
>>> print(module2.answer)
o Output of the above program
>>> What is the meaning of Life, the Universe, and Everything?
>>> What is your quest?
>>> 42
>>> To seek the holy grail.
Python Programming(1BPLCK105B) - Module 4: Modules | Mutable versus Immutable & Aliasing
Object-Oriented Programming(OOP)
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 11
o In the above program, the two variables with names question and answer
are used in both the modules without conflict, because they are located in
different spaces.
o Example 2: Functions also have their own namespaces:
Program
Output
o In the above program, the three n’s here do not collide since they are
each in a different namespace—they are three names for three different
variables, just like there might be three different instances
o Namespaces permit several programmers to work on the same project
without having naming collisions
Python Programming(1BPLCK105B) - Module 4: Modules | Mutable versus Immutable & Aliasing
Object-Oriented Programming(OOP)
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 12
8.6 Scope and lookup rules(LEGB Rules)
o The scope of an identifier is the region of program code in which the
identifier can be accessed or used
o Python defines four levels of scope:
1. Local (L) Scope:
- This is the innermost scope.
- Names defined within a function (e.g., function parameters,
variables assigned inside the function) are local to that function and
are only accessible within its body.
2. Enclosing (E) Scope:
- This applies to nested functions.
- If a name is not found in the local scope of an inner function,Python
searches the enclosing scope of any outer functions.
3. Global (G) Scope:
- Names defined at the top level of a module (outside of any function
or class) are global.
- They are accessible throughout the entire module.
4. Built-in (B) Scope:
- This is the broadest scope, encompassing Python's predefined
names, such as print(), len(), and str().
- These names are always available without needing explicit
definition or import.
o Python uses precedence (LEGB) rules: The same name could occur in
more than one of these scopes, but the innermost, or local scope, will
always take precedence over the global scope, and the global scope
always gets used in preference to the built-in scope. Let’s start with a
simple example 1
Program
Python Programming(1BPLCK105B) - Module 4: Modules | Mutable versus Immutable & Aliasing
Object-Oriented Programming(OOP)
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 13
o This program gives different outputs because the same variable
name pi resides in different namespaces, one inside the
function print_pi and the other in the upper level.
o When print_pi() gets executed, 'inner pi variable' is printed as that
is pi value inside the function namespace.
o The value 'outer pi variable' is printed when pi is referenced in the
outer namespace.
o From this example, we can guess that there definitely is a rule that is
followed to decide from which namespace a variable has to be picked.
▪ Example 2
Program :
o This prints 17 10 3. The reason is that the two variables m and n in
lines 1 and 2 are outside the function in the global namespace.
o Within the body of f, the scope lookup rules determine that we use
the local variables m and n.
o Notice too that the def puts name f into the global namespace here.
So it can be called online last.
8.8 Three import statement variants
o Here are three different ways to import names into the current
namespace, and to use them: direct, alias, or all-at-once.
o Import statement variants allow developers to bring external code into a
program, primarily differing by what they import (module, specific
functions).
o Common styles in Python like
1. import math
2. import numpy as np
3. from math import pi
Python Programming(1BPLCK105B) - Module 4: Modules | Mutable versus Immutable & Aliasing
Object-Oriented Programming(OOP)
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 14
▪ Common Python Import Variants
1. import module: Imports the entire module; use module.function() to
access members.
>>> import math
>>> print(math.pi)
2. import module as alias: Imports the module and assigns it a shorter
name (alias).
>>> import numpy as np
>>> arr = np.array([1, 2, 3])
3. from module import name: Imports a specific function, class, or
variable directly into the current namespace.
>>> from math import sqrt
>>> print(sqrt(16))
o from module import *: Imports all public names from the module into
the current namespace (use with caution).
>>> from math import *
>>> print(pi) # pi is directly available
CHAPTER 9: More Datatypes
9.1 Mutable versus Immutable & Aliasing
▪ Mutable datatypes: In Python, mutable data types are those whose
value or state can be modified after they are created. Lists and
dictionaries are good examples of mutable data types. Example
>>> my_list = [2, 4, 5, 3, 6, 1]
>>> my_list[0] = 9
>>> my_list
[9, 4, 5, 3, 6, 1]
▪ Immutable datatypes: Tuples and strings are examples of immutable
datatypes; their contents can not be changed after they have been
created:
>>> my_tuple = (2, 5, 3, 1)
>>> my_tuple[0] = 9
Traceback (most recent call last):
File "<interactive input>", line 2, in <module>
TypeError: 'tuple' object does not support item assignment
Python Programming(1BPLCK105B) - Module 4: Modules | Mutable versus Immutable & Aliasing
Object-Oriented Programming(OOP)
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 15
▪ Aliasing: In Python, aliasing occurs when multiple variables (names)
refer to the same object in memory. Changes made through one alias are
reflected in all other aliases because they all point to the same
underlying data. This can lead to unexpected "mutation at a distance" if
not handled carefully.Mutability is usually useful, but it may lead to
aliasing. In this case, two variables refer to the same object and
mutating one will also change the other. Example
>>> list_one = [1, 2, 3, 4, 6]
>>> list_two = list_one
>>> list_two[-1] = 5
>>> list_one
[1, 2, 3, 4, 5]
o This happens because both list_one and list_two refer to the same
memory address containing the actual list. We can check this using
the built-in function id:
>>> list_one = [1, 2, 3, 4, 6]
>>> list_two = list_one
>>> print(list_one is list_two)
True
>>> id(list_one) == id(list_two)
True
o We can solve the aliasing problem by making a copy of the list
using the slicing operator
>>> list_one = [1, 2, 3, 4, 6]
>>> list_two = list_one[:]
>>> id(list_one) == id(list_two)
False
>>> list_two[-1] = 5
>>> list_two
[1, 2, 3, 4, 5]
>>> list_one
[1, 2, 3, 4, 6]
Note: However, this will not work for nested lists for the same reason. The
module copy provides functions to solve this.
Python Programming(1BPLCK105B) - Module 4: Modules | Mutable versus Immutable & Aliasing
Object-Oriented Programming(OOP)
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 16
CHAPTER 11: CLASSES AND OBJECTS
11.1 Classes and Objects: the Basics
11.1.1 Introduction to Object-Oriented Programming(OOP)
o An object-oriented programming (OOP) language is a programming
paradigm that structures code around "objects," which are data
structures containing both data and procedures.
o These languages are used to create reusable and efficient
applications by modelling real-world entities
o In object-oriented programming, the focus is on the creation of objects
that contain both data and functionality.
o Examples include Java, Python, C++, JavaScript, and C#.
▪ Advantages of OOPs
o Easier maintenance and improved program organisation.
o OOP enables applications to be more flexible and extensible.
o It promotes code reuse, which helps to reduce development costs.
o It makes it easier to write modular code.
o It’s possible to write code that can be reorganised and reused without
affecting other parts of the program.
o It is possible to build complex applications with fewer lines of code.
o It offers a greater degree of customisation in the applications.
11.1.2 User-defined compound data types: Classes and objects
▪ What are classes?
o A class is a user-defined blueprint or template for creating objects.
o A class is are prototype created by a programmer for an object.
o A class is a model or plan to create an object.
o Classes are the design factory for an object.
o Classes bundle data (attributes) and functionality (methods)
together into a single, organised unit to model real-world entities.
▪ Key Components of a Class: The class contains Two members
1. attributes(fields/properties) (data/state):
- These are the variables that hold the state of an object created
from the class. Attributes define the properties of the object.
- For example, in the “car” class, attributes include colour, make,
model and year.
Python Programming(1BPLCK105B) - Module 4: Modules | Mutable versus Immutable & Aliasing
Object-Oriented Programming(OOP)
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 17
2. methods (functions) (behaviour):
- These are functions defined within the class that describe the
behaviours or actions that an object created from the class can
perform.
- For example, in the ‘car’ class, methods might include start(),
stop(), accelerate(), horn(), etc.
▪ The syntax rules for a class definition are:
o Classes are created by the keyword class.
o There is a header that begins with the keyword, class, followed by
the class's name, and ends with a colon.
o Example:
>>> class MyClass:
▪ What are Objects?
o In Python, an object is an instance of a class.
o Each object contains data (variables) and methods to operate on that
data. It is the fundamental abstraction for data.
o Example:
Program Output
o In the above example Car class defines a blueprint for car objects.
The __init__() constructor initialises the model and price attributes,
using self to refer to the current object. Audi is the name of the object.
When Audi = Car("R8", 100000) is executed, "R8" is assigned to
model and 100000 to price.These attributes are accessed via dot
notation, like Audi.model and Audi.price.
o Accessing class members: We can access both instance variables and
methods of a class using an object. Instance variables are unique to each
object, while methods define the behaviour of the objects.
Python Programming(1BPLCK105B) - Module 4: Modules | Mutable versus Immutable & Aliasing
Object-Oriented Programming(OOP)
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 18
▪ User-defined types:
o A class creates a new type, and the object is an instance (or variable) of
that class. One can create any number of objects for a class.
o Let's create a new user-defined type called Point that represents a point
in two-dimensional space.
o For example, (0, 0) represents the origin, and (x, y) represents the
point x units to the right and y units up from the origin.
o Some of the typical operations that one associates with points might be
calculating the
a. Distance of a point from the origin, or from another point.
b. Finding the midpoint of two points.
c. Asking if a point falls within a given rectangle or circle.
o A class definition looks like
o The program, header, which begins with the keyword class, followed by
the name of the class, and ending with a colon. Indentation levels tell
us where the class ends.
o If the first line after the class header is a string, it becomes the docstring
of the class and will be recognised by various tools.
o Every class should have a method with the special name __init__. This
initialiser method is automatically called whenever a new instance of
Point is created. It allows the programmer to set up the attributes
required within the new instance by giving them their initial state/values.
o The self is the convention and is automatically set to reference the
newly created object that needs to be initialised.
o use our new Point class now:
o The output of the program is (0,0,0,0)
Python Programming(1BPLCK105B) - Module 4: Modules | Mutable versus Immutable & Aliasing
Object-Oriented Programming(OOP)
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 19
11.1.3 Attributes
o Attributes are variables that belong to an object and contain information
about its properties and characteristics.
o Classes in Python have two types of attributes, viz., class attributes and
instance attributes.
o Class attributes are defined inside the class (usually, immediately after
the class header).
o Any number of objects can be created from the class. That is, they are
shared by all the objects created from that class.
o Attributes of one instance are not available for another instance of the
same class.
o An object can contain named elements known as instance attributes.
o One can assign values to these attributes using the dot operator.
>>> p.x = 3
>>> p.y = 4
o A state diagram that shows an object and its attributes is called an object
diagram. It is shown below
o The variable p refers to a Point object, which contains two attributes.
Each attribute refers to a number. We can access the value of an
attribute using the same syntax:
>>> print(p.y)
4
>>> x = p.x
>>> print(x)
3
o The expression p.x means, “Go to the object p refers to and get the
value of x”. In this case, we assign that value to a variable named x.
There is no conflict between the variable x (in the global namespace
here) and the attribute x
o We can use dot notation as part of any expression
>>> print("(x={0}, y={1})".format(p.x, p.y))
>>> distance_squared_from_origin = p.x * p.x + p.y * p.y
o The first line outputs (x=3, y=4). The second line calculates the
value 25.
P
Python Programming(1BPLCK105B) - Module 4: Modules | Mutable versus Immutable & Aliasing
Object-Oriented Programming(OOP)
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 20
11.1.4 Improving our initialiser
o The built-in methods are used to improve the initialiser in the classes and
objects is __init__ method
o The __init__ method is a special method in Python that initialises the
object when it is created.
o It is also known as the constructor and is used in Python classes.
o It is called automatically when an object is created from a class and
allows us to initialise the attributes of the object.
o The name “__init__” is a convention in Python that stands for
“initialise.”
o Example: __init__ method
o To create a point at position (7, 6) currently needs three lines of code:
>>> p = Point()
>>> p.x = 7
>>> p.y = 6
o We can make our class constructor more general by placing extra
parameters into the __init__ method, as shown in the example below:
o The x and y parameters here are both optional. If the caller does not
supply arguments, they’ll get the default values of 0. Here is our
improved class in action:
Python Programming(1BPLCK105B) - Module 4: Modules | Mutable versus Immutable & Aliasing
Object-Oriented Programming(OOP)
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 21
11.1.5 Adding other methods to our class
o A method behaves like a function, but it is invoked on a specific instance.
o Let’s add another method, distance_from_origin, to see better how
methods work. Like a data attribute, methods are accessed using dot
notation. Let’s add another method, distance_from_origin, to see better
how methods work:
o Let’s create a few point instances, look at their attributes, and call our
new method on them.
Python Programming(1BPLCK105B) - Module 4: Modules | Mutable versus Immutable & Aliasing
Object-Oriented Programming(OOP)
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 22
11.1.7 Converting an instance to a string
o To convert an instance to a string, you typically use a built-in function or
method specific to the programming language you are using.
o These functions often call a special method defined within the object's
class to provide a meaningful string representation.
o We can define these special methods in our own classes to control the
output when an instance is converted to a string.
11.1.8 Instances as return values
o Functions and methods can return instances. For example, given two
Point objects, find their midpoint. First, we’ll write this as a regular
function:
o The function creates and returns a new Point object:
o Now let us do this as a method instead. Suppose we have a point object,
and wish to find the midpoint halfway between it and some other target
point:
Python Programming(1BPLCK105B) - Module 4: Modules | Mutable versus Immutable & Aliasing
Object-Oriented Programming(OOP)
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 23
o This method is identical to the function, aside from some renaming. It’s
usage might be like this:
o While this example assigns each point to a variable, this need not be
done. Just as function calls are composable, method calls, and object
instantiation are also composable, leading to this alternative that uses no
variables:
Module 4: Question Bank
1. What is a module in Python? Why are modules useful in large programs?**
2. Explain the use of the random module. Write a program to generate:*****
o a random integer between 1 and 100
o a random floating-point number between 0 and 1
3. Describe the time module. Write a program to measure the execution time of a
simple loop.
4. Explain the math module. List any five functions available in the math module with
examples.*****
5. Differentiate between the functions random.random(), random.randint() and
random.choice().
6. What does it mean to create your own module? Write steps and a simple example
to create and use a user-defined module.**
7. Explain namespaces in Python. How do namespaces help avoid name conflicts?
8. Describe Python’s scope and lookup rules (LEGB rule) with a suitable
Python Programming(1BPLCK105B) - Module 4: Modules | Mutable versus Immutable & Aliasing
Object-Oriented Programming(OOP)
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 24
example.****
9. What are attributes in Python? Explain the dot operator with reference to modules
and objects.
10.Explain the three variants of the import statement in Python with examples.
Mention one advantage of each.*****
11.What is the difference between mutable and immutable objects in Python? Give
examples.
12.Explain aliasing. How does aliasing affect mutable objects?*****
13.Write a program that demonstrates aliasing with a list and explain the output.
14.Why are strings considered immutable? Illustrate with an example.
15.Define Object Oriented Programming (OOP). What are the advantages of using
OOP in Python?*****
16.What is a class and an object? Write a simple class and create two objects from it.
17.Explain attributes in a class. Differentiate between instance attributes and class
attributes.*****
18.Write a class with a method and explain how methods are added to a class.***
19.Explain how instances can be used as arguments and return values in methods.
Write a suitable example.
20.What is the purpose of converting an instance to a string? Explain the use of the
__str__() method with an example.*****
Acknowledgement:
My sincere thanks to the authors Peter Wentworth, Jeffrey Elkner, Allen B.
Downey and Chris Meyers- because the above contents are prepared from their
textbook “How to think like a computer scientist: learning with Python 3”.
Green Tea Press, Wellesley, Massachusetts,2020
Prepared by:
Dr. Suresha V
Professor & Principal
Dept. of Electronics and Communication Engineering.
Reach me at: suresha.vee@gmail.com
WhatsApp: +91 8310992434

Module 4 python programming-1BPLCK105B-2025 by Dr.SV.pdf

  • 1.
    Dr. SURESHA V ASimplified Notes As per VTU Syllabus 2025 Scheme PYTHON PROGRAMMING Code: 1BPLCK105B/205B Professor & Principal Dept. of E&CE K.V.G. College of Engineering, Sullia, D.K-574 327 Affiliated to Visvesvaraya Technological University Belagavi - 590018 MODULE 4 Modules | Mutable versus Immutable & Aliasing Object-Oriented Programming (OOP) Strings, Tuples and Lists
  • 2.
    Python Programming(1BPLCK105B) -Module 4: Modules | Mutable versus Immutable & Aliasing Object-Oriented Programming(OOP) Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 1 MODULE 4 Modules | Mutable versus Immutable & Aliasing Object-Oriented Programming(OOP) Syllabus: ▪ 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. Chapter: 8.1-8.8, 9.1, 11.1 Text Book: Peter Wentworth, Jeffrey Elkner, Allen B. Downey and Chris Meyers- How to think like a computer scientist: learning with python 3. Green Tea Press, Wellesley, Massachusetts,2020 Chapter 8: MODULES 8.1 Introduction o A module is a single Python file with a .py extension that serves as an organisational unit of code. o It can define functions, classes, variables, and executable statements that can then be imported and used in other Python programs. o The following modules are learn in this section are 1. The random numbers Module 2. The time Module 3. The math Module 8.2 The random numbers Module o Python has a built-in module that you can use to make random numbers. o It is a built-in library that provides functions for generating pseudo- random numbers and performing random operations. o It introduces randomness into programs.
  • 3.
    Python Programming(1BPLCK105B) -Module 4: Modules | Mutable versus Immutable & Aliasing Object-Oriented Programming(OOP) Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 2 ▪ Random numbers: A few typical uses are 1. To play a game of chance where the computer needs to throw some dice, pick a number, or flip a coin. 2. To shuffle a deck of playing cards randomly. 3. To allow/make an enemy spaceship appear at a random location and start shooting at the player. 4. To simulate possible rainfall when we make a computerised model for estimating the environmental impact of building a dam. 5. For encrypting banking sessions on the Internet. ▪ random module: *** o It is a built-in library used for generating pseudo-random numbers for various non-security-related applications like simulations, games, and testing. o It provides functions for generating random integers, floats, and making random selections from sequences. o The random module has a set of methods shown below Method Description random() Returns a random float number between 0 and 1 randint() Returns a random number between the given range randrange() Returns a random number between the given range seed() Initialise the random number generator shuffle() Takes a sequence and returns the sequence in a random order sample() Returns a given sample of a sequence uniform() Returns a random float number between two given parameters choice() Returns a random element from the given sequence ▪ Examples of Random Module: import the random module in a program 1. random() method: o It is a built-in method in a random module. o It generates a random float number between 0.0 and 1.0 o Examples: Program Output
  • 4.
    Python Programming(1BPLCK105B) -Module 4: Modules | Mutable versus Immutable & Aliasing Object-Oriented Programming(OOP) Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 3 2. randrange() Method: o It is a built-in method in a random module. o It generates a random number between the given range o Syntax: random.randrange(start, end,step) o Examples: Program Output 7 2 93 21 3. shuffle() Method: o It is a built-in method in a random module. o Takes a sequence and returns the sequence in a random order. o Example: Program Output ['apple','cherry', 'banana'] [17, 35, 46, 4, 40, 23, 20, 29, 33, 36, 38, 48, 2, 12, 51, 18, 21, 9, 1, 6, 7, 45, 22, 43, 15, 24, 8, 11, 50, 25, 32, 13, 49, 41, 39, 19, 44, 31, 3, 42, 27, 30, 10, 5, 14, 28, 34, 26, 47, 0, 16, 37] 4. shuffle() Method: o Takes a sequence and returns the sequence in a random order. Example Program Output M (run the code for the first time)
  • 5.
    Python Programming(1BPLCK105B) -Module 4: Modules | Mutable versus Immutable & Aliasing Object-Oriented Programming(OOP) Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 4 L (run the same code a second time) 88 (run the code for the first time) 71 (run the same code a second time) 8.2.1 Repeatability and Testing o Repeatability:Ability to produce the same sequence of numbers multiple times. o Random number generators are based on a deterministic algorithm — repeatable and predictable. So they’re called pseudo-random generators — they are not genuinely random. o They start with a seed value. Each time you ask for another random number, you’ll get one based on the current seed attribute, and the state of the seed (which is one of the attributes of the generator) will be updated. ▪ seed() Method: o The seed() method is used to initialise the random number generator. o It creates a random number generator and gives an explicit seed value to object. o The random number generator requires a starting value (a seed) to generate a random number. Without this argument, the system probably uses something based on the time. Example: Program to generate a random number with a seed o
  • 6.
    Python Programming(1BPLCK105B) -Module 4: Modules | Mutable versus Immutable & Aliasing Object-Oriented Programming(OOP) Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 5 o Output will be identical for both "First run" and "Second run" sections. 8.1.2 Picking balls from bags, throwing dice, shuffling a pack of cards o Random module may be used to generate random numbers, print a random value from a list or string, and so on in the above applications o Here is an example to generate a list containing n random integers between a lower and an upper bound. Program: Output: 1 First Run Output: 2 Second Run o After running the same program, we generated five random numbers, and every run produced different results. But notice that we got a duplicate in the result. Often, this is wanted, for example, when we throw a die five times, we would expect some duplicates. o Suppose we wanted five numbers between one and ten million, without duplicates. Generating a list of ten million items
  • 7.
    Python Programming(1BPLCK105B) -Module 4: Modules | Mutable versus Immutable & Aliasing Object-Oriented Programming(OOP) Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 6 Program: Output: 1 First Run Output: 2 Second Run 8.2 The time module o The time module provides functions for working with time values and delays. o Use it to measure 1. elapsed time 2. add delays 3. format timestamps, or convert between time representations. o The time module in Python provides various functions for working with time, including measuring time intervals, pausing program execution, and formatting time representations. o The time module has a function called clock that is recommended for measuring the processor, the current time,sleep time, and elapsed time.
  • 8.
    Python Programming(1BPLCK105B) -Module 4: Modules | Mutable versus Immutable & Aliasing Object-Oriented Programming(OOP) Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 7 o Whenever the clock is called, it returns a floating-point number representing how many seconds have elapsed since your program started running. o Example: Get the current time and sleep for 5 seconds Program Output Start time: 1767088974.210592 Elapsed: 5.00 seconds ▪ time.clock() method was used for measuring processor time or elapsed time, depending on the operating system. time.clock() method of the time module in Python is used to get the current processor time as a floating point number expressed in seconds. ▪ Write a Python code to measure the program execution time of a given processor to sum the elements in a list, which has a million elements... Ans: Consider a variable t0 to be the start time and t1 to be the end time. The difference t1-t0 is the time elapsed, and is a measure of how fast your program is running.
  • 9.
    Python Programming(1BPLCK105B) -Module 4: Modules | Mutable versus Immutable & Aliasing Object-Oriented Programming(OOP) Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 8 o Program: o Output: o So our function runs about 57% slower than the built-in one. Generating and summing up ten million elements in under a second. 8.3 The math module o Python has a built-in module that you can use for mathematical tasks. o This module contains the kinds of mathematical functions like sin, cos, sqrt, log, log10 and some mathematical constants like pi and e: o Examples >>> import math >>> math.pi # Constant pi 3.141592653589793 >>> math.e # Constant natural log base 2.718281828459045
  • 10.
    Python Programming(1BPLCK105B) -Module 4: Modules | Mutable versus Immutable & Aliasing Object-Oriented Programming(OOP) Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 9 >>> math.sqrt(2.0) # Square root function 1.4142135623730951 >>> math.radians(90) # Convert 90 degrees to radians 1.5707963267948966 >>> math.sin(math.radians(90)) # Find sin of 90 degrees 1.0 >>> math.asin(1.0) * 2 # Double the arcsin of 1.0 to get pi 3.141592653589793 o There are two functions radians and degrees to convert between these two popular ways of measuring angles. o Mathematical functions are “pure” and don’t have any state — calculating the square root of 2.0 doesn’t depend on any kind of state or history about what happened in the past. o So the functions are not methods of an object—they are simply functions that are grouped in a module called math. 8.4 Creating your own modules o Creating your own modules in Python involves saving Python code in a file with a .py extension. This file then acts as a reusable library that can be imported and used in other Python scripts. Create a new file with a .py extension. o For example, my_module.py. Define functions, classes, or variables. Inside this file, define the functions, classes, or variables that you want to make available for use in other scripts.Suppose,for example, this script is saved as a file named mymodule.py
  • 11.
    Python Programming(1BPLCK105B) -Module 4: Modules | Mutable versus Immutable & Aliasing Object-Oriented Programming(OOP) Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 10 o Now we can use our module, both in scripts we write and in the interactive Python interpreter. To do so, we must first import the module name mymodule in the scripts. o The use of modules makes it possible to break up very large programs into manageable-sized parts, and to keep related parts together. 8.5 Namespaces o A namespace is a collection of identifiers that belong to a module, or to a function. o A Namespace in Python is a container that holds a set of identifiers (variable names) and their associated objects (values). o To put it simply, a namespace is a collection of names. o A Python namespace is a mapping from names to objects. o Each module has its own namespace, so we can use the same identifier name in multiple modules without causing an identification problem. o This allows us to use the same name for different variables or objects in different parts of our code, without causing any conflicts or confusion. o Let's consider two separate modules that are created with a module name, module1.py and module2.py # module1.py >>> question = "What is the meaning of Life, the Universe, and Everything?" >>> answer = 42 # module2.py >>> question = "What is your quest?" >>> answer = "To seek the holy grail." o We can now import both modules and access questions and answers in each: >>> import module1 >>> import module2 >>> print(module1.question) >>> print(module2.question) >>> print(module1.answer) >>> print(module2.answer) o Output of the above program >>> What is the meaning of Life, the Universe, and Everything? >>> What is your quest? >>> 42 >>> To seek the holy grail.
  • 12.
    Python Programming(1BPLCK105B) -Module 4: Modules | Mutable versus Immutable & Aliasing Object-Oriented Programming(OOP) Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 11 o In the above program, the two variables with names question and answer are used in both the modules without conflict, because they are located in different spaces. o Example 2: Functions also have their own namespaces: Program Output o In the above program, the three n’s here do not collide since they are each in a different namespace—they are three names for three different variables, just like there might be three different instances o Namespaces permit several programmers to work on the same project without having naming collisions
  • 13.
    Python Programming(1BPLCK105B) -Module 4: Modules | Mutable versus Immutable & Aliasing Object-Oriented Programming(OOP) Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 12 8.6 Scope and lookup rules(LEGB Rules) o The scope of an identifier is the region of program code in which the identifier can be accessed or used o Python defines four levels of scope: 1. Local (L) Scope: - This is the innermost scope. - Names defined within a function (e.g., function parameters, variables assigned inside the function) are local to that function and are only accessible within its body. 2. Enclosing (E) Scope: - This applies to nested functions. - If a name is not found in the local scope of an inner function,Python searches the enclosing scope of any outer functions. 3. Global (G) Scope: - Names defined at the top level of a module (outside of any function or class) are global. - They are accessible throughout the entire module. 4. Built-in (B) Scope: - This is the broadest scope, encompassing Python's predefined names, such as print(), len(), and str(). - These names are always available without needing explicit definition or import. o Python uses precedence (LEGB) rules: The same name could occur in more than one of these scopes, but the innermost, or local scope, will always take precedence over the global scope, and the global scope always gets used in preference to the built-in scope. Let’s start with a simple example 1 Program
  • 14.
    Python Programming(1BPLCK105B) -Module 4: Modules | Mutable versus Immutable & Aliasing Object-Oriented Programming(OOP) Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 13 o This program gives different outputs because the same variable name pi resides in different namespaces, one inside the function print_pi and the other in the upper level. o When print_pi() gets executed, 'inner pi variable' is printed as that is pi value inside the function namespace. o The value 'outer pi variable' is printed when pi is referenced in the outer namespace. o From this example, we can guess that there definitely is a rule that is followed to decide from which namespace a variable has to be picked. ▪ Example 2 Program : o This prints 17 10 3. The reason is that the two variables m and n in lines 1 and 2 are outside the function in the global namespace. o Within the body of f, the scope lookup rules determine that we use the local variables m and n. o Notice too that the def puts name f into the global namespace here. So it can be called online last. 8.8 Three import statement variants o Here are three different ways to import names into the current namespace, and to use them: direct, alias, or all-at-once. o Import statement variants allow developers to bring external code into a program, primarily differing by what they import (module, specific functions). o Common styles in Python like 1. import math 2. import numpy as np 3. from math import pi
  • 15.
    Python Programming(1BPLCK105B) -Module 4: Modules | Mutable versus Immutable & Aliasing Object-Oriented Programming(OOP) Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 14 ▪ Common Python Import Variants 1. import module: Imports the entire module; use module.function() to access members. >>> import math >>> print(math.pi) 2. import module as alias: Imports the module and assigns it a shorter name (alias). >>> import numpy as np >>> arr = np.array([1, 2, 3]) 3. from module import name: Imports a specific function, class, or variable directly into the current namespace. >>> from math import sqrt >>> print(sqrt(16)) o from module import *: Imports all public names from the module into the current namespace (use with caution). >>> from math import * >>> print(pi) # pi is directly available CHAPTER 9: More Datatypes 9.1 Mutable versus Immutable & Aliasing ▪ Mutable datatypes: In Python, mutable data types are those whose value or state can be modified after they are created. Lists and dictionaries are good examples of mutable data types. Example >>> my_list = [2, 4, 5, 3, 6, 1] >>> my_list[0] = 9 >>> my_list [9, 4, 5, 3, 6, 1] ▪ Immutable datatypes: Tuples and strings are examples of immutable datatypes; their contents can not be changed after they have been created: >>> my_tuple = (2, 5, 3, 1) >>> my_tuple[0] = 9 Traceback (most recent call last): File "<interactive input>", line 2, in <module> TypeError: 'tuple' object does not support item assignment
  • 16.
    Python Programming(1BPLCK105B) -Module 4: Modules | Mutable versus Immutable & Aliasing Object-Oriented Programming(OOP) Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 15 ▪ Aliasing: In Python, aliasing occurs when multiple variables (names) refer to the same object in memory. Changes made through one alias are reflected in all other aliases because they all point to the same underlying data. This can lead to unexpected "mutation at a distance" if not handled carefully.Mutability is usually useful, but it may lead to aliasing. In this case, two variables refer to the same object and mutating one will also change the other. Example >>> list_one = [1, 2, 3, 4, 6] >>> list_two = list_one >>> list_two[-1] = 5 >>> list_one [1, 2, 3, 4, 5] o This happens because both list_one and list_two refer to the same memory address containing the actual list. We can check this using the built-in function id: >>> list_one = [1, 2, 3, 4, 6] >>> list_two = list_one >>> print(list_one is list_two) True >>> id(list_one) == id(list_two) True o We can solve the aliasing problem by making a copy of the list using the slicing operator >>> list_one = [1, 2, 3, 4, 6] >>> list_two = list_one[:] >>> id(list_one) == id(list_two) False >>> list_two[-1] = 5 >>> list_two [1, 2, 3, 4, 5] >>> list_one [1, 2, 3, 4, 6] Note: However, this will not work for nested lists for the same reason. The module copy provides functions to solve this.
  • 17.
    Python Programming(1BPLCK105B) -Module 4: Modules | Mutable versus Immutable & Aliasing Object-Oriented Programming(OOP) Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 16 CHAPTER 11: CLASSES AND OBJECTS 11.1 Classes and Objects: the Basics 11.1.1 Introduction to Object-Oriented Programming(OOP) o An object-oriented programming (OOP) language is a programming paradigm that structures code around "objects," which are data structures containing both data and procedures. o These languages are used to create reusable and efficient applications by modelling real-world entities o In object-oriented programming, the focus is on the creation of objects that contain both data and functionality. o Examples include Java, Python, C++, JavaScript, and C#. ▪ Advantages of OOPs o Easier maintenance and improved program organisation. o OOP enables applications to be more flexible and extensible. o It promotes code reuse, which helps to reduce development costs. o It makes it easier to write modular code. o It’s possible to write code that can be reorganised and reused without affecting other parts of the program. o It is possible to build complex applications with fewer lines of code. o It offers a greater degree of customisation in the applications. 11.1.2 User-defined compound data types: Classes and objects ▪ What are classes? o A class is a user-defined blueprint or template for creating objects. o A class is are prototype created by a programmer for an object. o A class is a model or plan to create an object. o Classes are the design factory for an object. o Classes bundle data (attributes) and functionality (methods) together into a single, organised unit to model real-world entities. ▪ Key Components of a Class: The class contains Two members 1. attributes(fields/properties) (data/state): - These are the variables that hold the state of an object created from the class. Attributes define the properties of the object. - For example, in the “car” class, attributes include colour, make, model and year.
  • 18.
    Python Programming(1BPLCK105B) -Module 4: Modules | Mutable versus Immutable & Aliasing Object-Oriented Programming(OOP) Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 17 2. methods (functions) (behaviour): - These are functions defined within the class that describe the behaviours or actions that an object created from the class can perform. - For example, in the ‘car’ class, methods might include start(), stop(), accelerate(), horn(), etc. ▪ The syntax rules for a class definition are: o Classes are created by the keyword class. o There is a header that begins with the keyword, class, followed by the class's name, and ends with a colon. o Example: >>> class MyClass: ▪ What are Objects? o In Python, an object is an instance of a class. o Each object contains data (variables) and methods to operate on that data. It is the fundamental abstraction for data. o Example: Program Output o In the above example Car class defines a blueprint for car objects. The __init__() constructor initialises the model and price attributes, using self to refer to the current object. Audi is the name of the object. When Audi = Car("R8", 100000) is executed, "R8" is assigned to model and 100000 to price.These attributes are accessed via dot notation, like Audi.model and Audi.price. o Accessing class members: We can access both instance variables and methods of a class using an object. Instance variables are unique to each object, while methods define the behaviour of the objects.
  • 19.
    Python Programming(1BPLCK105B) -Module 4: Modules | Mutable versus Immutable & Aliasing Object-Oriented Programming(OOP) Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 18 ▪ User-defined types: o A class creates a new type, and the object is an instance (or variable) of that class. One can create any number of objects for a class. o Let's create a new user-defined type called Point that represents a point in two-dimensional space. o For example, (0, 0) represents the origin, and (x, y) represents the point x units to the right and y units up from the origin. o Some of the typical operations that one associates with points might be calculating the a. Distance of a point from the origin, or from another point. b. Finding the midpoint of two points. c. Asking if a point falls within a given rectangle or circle. o A class definition looks like o The program, header, which begins with the keyword class, followed by the name of the class, and ending with a colon. Indentation levels tell us where the class ends. o If the first line after the class header is a string, it becomes the docstring of the class and will be recognised by various tools. o Every class should have a method with the special name __init__. This initialiser method is automatically called whenever a new instance of Point is created. It allows the programmer to set up the attributes required within the new instance by giving them their initial state/values. o The self is the convention and is automatically set to reference the newly created object that needs to be initialised. o use our new Point class now: o The output of the program is (0,0,0,0)
  • 20.
    Python Programming(1BPLCK105B) -Module 4: Modules | Mutable versus Immutable & Aliasing Object-Oriented Programming(OOP) Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 19 11.1.3 Attributes o Attributes are variables that belong to an object and contain information about its properties and characteristics. o Classes in Python have two types of attributes, viz., class attributes and instance attributes. o Class attributes are defined inside the class (usually, immediately after the class header). o Any number of objects can be created from the class. That is, they are shared by all the objects created from that class. o Attributes of one instance are not available for another instance of the same class. o An object can contain named elements known as instance attributes. o One can assign values to these attributes using the dot operator. >>> p.x = 3 >>> p.y = 4 o A state diagram that shows an object and its attributes is called an object diagram. It is shown below o The variable p refers to a Point object, which contains two attributes. Each attribute refers to a number. We can access the value of an attribute using the same syntax: >>> print(p.y) 4 >>> x = p.x >>> print(x) 3 o The expression p.x means, “Go to the object p refers to and get the value of x”. In this case, we assign that value to a variable named x. There is no conflict between the variable x (in the global namespace here) and the attribute x o We can use dot notation as part of any expression >>> print("(x={0}, y={1})".format(p.x, p.y)) >>> distance_squared_from_origin = p.x * p.x + p.y * p.y o The first line outputs (x=3, y=4). The second line calculates the value 25. P
  • 21.
    Python Programming(1BPLCK105B) -Module 4: Modules | Mutable versus Immutable & Aliasing Object-Oriented Programming(OOP) Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 20 11.1.4 Improving our initialiser o The built-in methods are used to improve the initialiser in the classes and objects is __init__ method o The __init__ method is a special method in Python that initialises the object when it is created. o It is also known as the constructor and is used in Python classes. o It is called automatically when an object is created from a class and allows us to initialise the attributes of the object. o The name “__init__” is a convention in Python that stands for “initialise.” o Example: __init__ method o To create a point at position (7, 6) currently needs three lines of code: >>> p = Point() >>> p.x = 7 >>> p.y = 6 o We can make our class constructor more general by placing extra parameters into the __init__ method, as shown in the example below: o The x and y parameters here are both optional. If the caller does not supply arguments, they’ll get the default values of 0. Here is our improved class in action:
  • 22.
    Python Programming(1BPLCK105B) -Module 4: Modules | Mutable versus Immutable & Aliasing Object-Oriented Programming(OOP) Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 21 11.1.5 Adding other methods to our class o A method behaves like a function, but it is invoked on a specific instance. o Let’s add another method, distance_from_origin, to see better how methods work. Like a data attribute, methods are accessed using dot notation. Let’s add another method, distance_from_origin, to see better how methods work: o Let’s create a few point instances, look at their attributes, and call our new method on them.
  • 23.
    Python Programming(1BPLCK105B) -Module 4: Modules | Mutable versus Immutable & Aliasing Object-Oriented Programming(OOP) Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 22 11.1.7 Converting an instance to a string o To convert an instance to a string, you typically use a built-in function or method specific to the programming language you are using. o These functions often call a special method defined within the object's class to provide a meaningful string representation. o We can define these special methods in our own classes to control the output when an instance is converted to a string. 11.1.8 Instances as return values o Functions and methods can return instances. For example, given two Point objects, find their midpoint. First, we’ll write this as a regular function: o The function creates and returns a new Point object: o Now let us do this as a method instead. Suppose we have a point object, and wish to find the midpoint halfway between it and some other target point:
  • 24.
    Python Programming(1BPLCK105B) -Module 4: Modules | Mutable versus Immutable & Aliasing Object-Oriented Programming(OOP) Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 23 o This method is identical to the function, aside from some renaming. It’s usage might be like this: o While this example assigns each point to a variable, this need not be done. Just as function calls are composable, method calls, and object instantiation are also composable, leading to this alternative that uses no variables: Module 4: Question Bank 1. What is a module in Python? Why are modules useful in large programs?** 2. Explain the use of the random module. Write a program to generate:***** o a random integer between 1 and 100 o a random floating-point number between 0 and 1 3. Describe the time module. Write a program to measure the execution time of a simple loop. 4. Explain the math module. List any five functions available in the math module with examples.***** 5. Differentiate between the functions random.random(), random.randint() and random.choice(). 6. What does it mean to create your own module? Write steps and a simple example to create and use a user-defined module.** 7. Explain namespaces in Python. How do namespaces help avoid name conflicts? 8. Describe Python’s scope and lookup rules (LEGB rule) with a suitable
  • 25.
    Python Programming(1BPLCK105B) -Module 4: Modules | Mutable versus Immutable & Aliasing Object-Oriented Programming(OOP) Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 24 example.**** 9. What are attributes in Python? Explain the dot operator with reference to modules and objects. 10.Explain the three variants of the import statement in Python with examples. Mention one advantage of each.***** 11.What is the difference between mutable and immutable objects in Python? Give examples. 12.Explain aliasing. How does aliasing affect mutable objects?***** 13.Write a program that demonstrates aliasing with a list and explain the output. 14.Why are strings considered immutable? Illustrate with an example. 15.Define Object Oriented Programming (OOP). What are the advantages of using OOP in Python?***** 16.What is a class and an object? Write a simple class and create two objects from it. 17.Explain attributes in a class. Differentiate between instance attributes and class attributes.***** 18.Write a class with a method and explain how methods are added to a class.*** 19.Explain how instances can be used as arguments and return values in methods. Write a suitable example. 20.What is the purpose of converting an instance to a string? Explain the use of the __str__() method with an example.***** Acknowledgement: My sincere thanks to the authors Peter Wentworth, Jeffrey Elkner, Allen B. Downey and Chris Meyers- because the above contents are prepared from their textbook “How to think like a computer scientist: learning with Python 3”. Green Tea Press, Wellesley, Massachusetts,2020 Prepared by: Dr. Suresha V Professor & Principal Dept. of Electronics and Communication Engineering. Reach me at: suresha.vee@gmail.com WhatsApp: +91 8310992434