Python Unit - 4 Notes
Python Unit - 4 Notes
Software objects :
Objects are the fundamental component of object-oriented
programming.
All values in Python are represented as objects.
Definition:
An object contains a set of attributes, stored in a set of instance variables, and
a set of functions called methods that provide its behavior.
Example : namelist.sort()
namelist object instance sort()method
OBJECT REFERENCE :
Definition :
• A reference is a value that references, or “points to,” the location of
another entity.
• Thus, when a new object in Python is created, two entities are stored—
the object, and a variable holding a reference to the object.
• All access to the object is through the reference value.
• The value that a reference points to is called the dereferenced value.
• A variable’s reference value can be determined with built-in function id.
>>>id(n) >>> id(k) >>> id(s)
505498136 505498136 505498296
The Assignment of References :
When variable n is assigned to k, it is the reference value of k that is assigned,
not the dereferenced value 20.
Copying a list :
• A copy of a list can be made as follows,
list2 = list(list1)
list() is referred to as a list constructor .
• A copy of the list structure has been made. Therefore, changes to the
list elements of list1 will not result in changes in list2.
>>>list1[0] = 5
>>>list2[0]
10
SHALLOW COPYING A LIST :
Lets consider the list,
list1 = [[10, 20], [30, 40], [50, 60]]
list2 = list(list1)
The resulting list structure after the assignment is :
Although copies were made of the top-level list structures, the elements
within each list were not copied.
This is referred to as a shallow copy .
Thus, if a top-level element of one list is reassigned, for example
list1[0] = [70, 80]
the other list would remain unchanged.
DEEP COPYING A LIST :
A deep copy operation of a list (structure) makes a copy of the complete
structure, including sublists.
Such an operation can be performed with the deep copy method of the copy
module,
import copy
list2 = copy. deepcopy (list1)
Turtle Graphics :
Turtle graphics refers to a means of controlling a graphical entity
(a “turtle”) in a graphics window with x,y coordinates.
There may be more than one turtle on the screen at once.
Each turtle is represented by a distinct object.
Absolute Positioning:
Method position returns a turtle’s current position.
For newly created turtles, this returns the tuple (0, 0).
A turtle’s position can be changed using absolute positioning by
moving the turtle to a specific x,y coordinate location by use of method
setposition.
The turtle is made invisible by a call to method hideturtle.
EXAMPLE PROGRAM :
Pen Attributes:
The pen attributes that can be controlled include whether
o the pen is down or up (using methods penup and pendown),
o the pen size (using method pensize), and
o the pen color (using method pencolor).
The pen attribute of a turtle object is related to its drawing
capabilities.
The most fundamental of these attributes is whether the pen is
currently “up” or “down,” controlled by methods penup() and
pendown().
When the pen attribute value is “up,” the turtle can be moved to
another location without lines being drawn.
This is especially needed when drawing graphical images with
disconnected segments.
EXAMPLE PROGRAM :
PENSIZE METHOD :
The pen size of a turtle determines the width of the lines drawn
when the pen attribute is “down.”
The pensize method is used to control this:
the_turtle.pensize(5)
The width is given in pixels, and is limited only by the size of the
turtle screen.
PENCOLOR METHOD :
The pen color can also be selected by use of the pencolor method:
the_turtle. pencolor('blue').
The name of any common color can be used, for example 'white',
'red', 'blue', 'green', 'yellow', 'gray', and 'black'.
Colors can also be specified in RGB (red/green/blue) component
values.
These values can be specified in the range 0–255
turtle.colormode(255)
the_turtle.pencolor(238, 130, 238) # violet
EXAMPLE :
Turtle Size :
The size of a turtle shape can be controlled with methods resizemode
and turtlesize
The first instruction sets the resize attribute of a turtle to ‘user’.
This allows the user (programmer) to change the size of the turtle by
use of method turtlesize.
The call to method turtlesize in the figure is passed two parameters.
The first is used to change the width of the shape , and the second
changes its length.
There are two other values that method resizemode may be set to.
An argument value of 'auto' causes the size of the turtle to change with
changes in the pen size/
Whereas a value of 'noresize' causes the turtle shape to remain the
same size.
EXAMPLE:
Turtle Shape :
A turtle may be assigned one of the following provided shapes: 'arrow',
'turtle', 'circle', 'square', 'triangle', and 'classic' (the default arrowhead
shape)
The shape and fill colors are set by use of the shape and fillcolor
methods,
the_turtle.shape('circle')
the_turtle.fi llcolor('white')
New shapes may be created and registered with (added to) the turtle
screen’s shape dictionary .
EXAMPLE :
Turtle Speed :
The speed of a turtle can be controlled by use of the speed method.
10: 'fast'
6: 'normal'
3: 'slow'
1: 'slowest'
0: 'fastest'
EXAMPLE :
the_turtle.speed(6)
the_turtle.speed('normal')
MODULES :
DEFINITION :
Programs are designed as a collection of modules.
The term “module”, refers to the design and/or implementation of
specific functionality to be incorporated into a program.
While an individual function may be considered a module, modules
generally consists of a collection of functions (or other entities).
Advantages of Modular Programming / uses of modules :
• SOFTWARE DESIGN:
It provides a means for the development of well designed programs.
• SOFTWARE DEVELOPMENT :
It provides a natural means of dividing up programming tasks.
It provides a means for the reuse of program code.
• SOFTWARE TESTING :
It provides a means of separately testing parts of a program.
It provides a means of integrating parts of a program during testing.
• SOTWARE MODIFICATION AND MAINTENANCE :
It facilitates the modification of specific program functionalities.
MODULAR DESIGN :
• Modular design allows large programs to be broken down into
manageable size parts.
• Each part (module) provides a clearly specified capability.
• It aids the software development process by providing an effective way
of separating programming tasks among various individuals or teams.
• It allows modules to be individually developed and tested, and
eventually integrated as a part of a complete system.
• Modular design facilitates program modification since the code
responsible for a given aspect of the software is contained within
specific modules.
Module Specification :
• A module’s interface is a specification of what it provides and how it is
to be used.
• Any program code making use of a given module is called a client of
the module.
• A module’s specification should be sufficiently clear and complete so
that its clients can effectively utilize it.
• A docstring is a string literal denoted by triple quotes used in Python
for providing the specification of certain program elements.
• Example :
def numPrimes(start, end):
“””Returns the number of primes between start and end.”””
• The function’s specification is provided by the line immediately
following the function header, called a docstring in Python.
• The docstring of a particular program element can be displayed by use
of the __doc__ extension.
>>>print(numPrimes .__doc__)
Returns the number of primes between start and end.
Top-Down Design :
• Top-down design is an approach for deriving a modular design in which
the overall design of a system is developed first, deferring the
specification of more detailed aspects of the design until later steps.
• One technique for dealing with the complexity of writing a complex
program is called Top-Down Design.
• In top-down design the programmer decides what major actions the
program must take and then rather than worry about the details of
how it is done, the programmer just defines a function that will handle
that later.
Python Modules :
• A Python module is a file containing Python definitions and
statements.
• When a Python fi le is directly executed, it is considered the main
module of a program.
• Main modules are given the special name __main__.
• Main modules provide the basis for a complete Python program.
• They may import (include) any number of other modules (and each of
those modules import other modules, etc.).
• Main modules are not meant to be imported into other modules.
• The Python Standard Library contains a set of predefined Standard
(built-in) modules.
•
import simple
simple.func1() This should be saved
simple.func2() Separately.
# module simple
print('module simple loaded’)
def func1():
print('func1 called’)
def func2():
print('func2 called’)
# mod1
def average(lst):
print('average of mod1 called')
# mod2
def average(lst):
mod1.average(10,20,30)
mod2.average(10,20,30)
Importing Modules : :
• In Python, the main module of any program is identified as the first
(“top-level”) module executed.
• When working interactively in the Python shell, the Python interpreter
functions as the main module, containing the global namespace. The
namespace is reset every time the interpreter is started.
• module __builtins__ is automatically imported in Python programs,
providing all the built-in constants, functions, and classes.
The “import modulename ” Form of Import :
• When using the import modulename form of import, the namespace of
the imported module becomes available to , but not part of , the
importing module.
• Using this form of import prevents any possibility of a name clash.
Example:
import math
math.factorial(5)
The “from-import” Form of Import :
• Python also provides an alternate import statement of the form
from modulename import something
where something can be a list of identifiers, a single renamed identifier, or an
asterisk.
(a) from modulename import func1, func2
(b) from modulename import func1 as new_func1
(c) from modulename import *
In example (a), only identifiers func1 and func2 are imported.
In example (b), only identifier func1 is imported, renamed as new_func1 in
the importing module.
Finally, in example (c), all of the identifiers are imported, except for those
that begin with two underscore characters.
The from modulename import func1 as new_func1 form of import is used
when identifiers in the imported module’s namespace are known to be
identical to identifiers of the importing module.
In such cases, the renamed imported function can be used without needing
to be fully qualified.
# module some
def f1(n):
return n*10
def f2(n1,n2):
return (n1 *n2)
# main
from some import *
print(f1(8))
print(f2(5,2))
Selecting Shell ➝ Restart Shell (Ctrl-F6) in the shell resets the namespace,
(after Restart Shell selected)
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
Local, Global, and Built-in Namespaces in Python :
• sum()
• max() global namespace functions
• min()
• math global namespace module
• Simple local namespace module
Text Files:
• A text file is a file containing characters, structured as lines of text.
• In addition to printable characters, text files also contain the
nonprinting newline character, \n, to denote the end of each text line.
• Thus, text files can be directly viewed and created using a text editor.
• A binary file is a file that is formatted in a way that only a computer
program can read.
• binary files can contain various types of data, such as numerical values,
and are therefore not structured as lines of text.
• Any attempt to directly view a binary file will result in “garbled”
characters on the screen.
FILE OPERATIONS
• Fundamental operations of all types of fi les include
• opening a fi le,
• closing a fi le
String Processing
• String processing refers to the operations performed on strings that
allow them to be accessed, analyzed, and updated.
String Traversal :
• The characters in a string can be easily traversed, without the use of an
explicit index variable, using the for chr in string form of the for
statement.
for chr in line:
if chr == space:
num_spaces = num_spaces + 1
String Methods:
Python provides a number of methods specific to strings, in addition to the
general sequence operations.
Exception Handling :
Various error messages can occur when executing Python programs. Such
errors are called exceptions
Python handle these errors by reporting them on the screen. Exceptions can
be “caught” and “handled” by a program , to either correct the error and
continue execution, or terminate the program.
Exception :
An exception is a value (object) that is raised (“thrown”) signaling that an
unexpected, or “exceptional,” situation has occurred.
Python contains a predefined set of exceptions referred to as standard
exceptions.
The standard exceptions are defi ned within the exceptions module of the
Python Standard Library, which is automatically imported into Python
programs.
EXAMPLE :
The Propagation of Raised Exceptions :
An exception is either handled by the client code, or automatically
propagated back to the client’s calling code, and so on, until handled. If an
exception is thrown all the way back to the main module (and not handled),
the program terminates displaying the details of the exception.
******************THE END**********************