0% found this document useful (0 votes)
96 views

Python Unit - 4 Notes

- An object is defined as something that has attributes and behaviors. Software objects in Python represent all values as objects with attributes stored in instance variables and behaviors defined as methods. - An object reference refers to the location of an object in memory. When a new object is created, a reference variable points to its location. All access is through the reference. - List assignment copies the reference, not the values. A shallow copy copies the top-level structure but not nested elements, while a deep copy fully replicates the nested structure.

Uploaded by

Anandhi Vijay
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
96 views

Python Unit - 4 Notes

- An object is defined as something that has attributes and behaviors. Software objects in Python represent all values as objects with attributes stored in instance variables and behaviors defined as methods. - An object reference refers to the location of an object in memory. When a new object is created, a reference variable points to its location. All access is through the reference. - List assignment copies the reference, not the values. A shallow copy copies the top-level structure but not nested elements, while a deep copy fully replicates the nested structure.

Uploaded by

Anandhi Vijay
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

UNIT-4

OBJECTS AND THEIR USE


OBJECTS :
• Definition :
An object is defined as something that has a set of attributes and a
related set of behaviors.
Example :
DOG is an object.
“AGE “, “BREED”,”COLOR”- Attributes
“BARK”, “EAT”, “ SLEEP” - Behavior

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.

This can be determined by use of the built-in id function.

variable k is assigned a reference value to a new memory location holding the


value 30.
The previous memory location that variable k referenced is retained since
variable n is still referencing it.
As a result, n and k point to different values, and therefore are no longer
equal.

Memory Deallocation and Garbage Collection :


Definition :
 To deallocate a memory location means to change its status from
“currently in use” to “available for reuse.”
 In Python, memory deallocation is automatically performed by a
process called garbage collection .
 Garbage collection is a method of determining which locations in
memory are no longer in use, and deallocating them.
 The garbage collection process is ongoing during the execution of a
Python program.

List Assignment and Copying :


• List Assignment:
• when a variable is assigned to another variable referencing a list,
each variable ends up referring to the same instance of the list in
memory.
• Any changes to the elements of list1 results in changes to list2.
>>> list1[0] = 5
>>>list2[0]
5

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.

Creating a Turtle Graphics Window:


 The import turtle form of import is used
 Each of the turtle graphics methods must be called in the form
turtle.Methodname
 The first method called, setup creates a graphics window of the
specified size (in pixels)
 To set the title of this window, we need the reference to this object.
 This is done by call to method Screen.
 The background color of the turtle window can be changed from the
default white background color.
 This is done using method bgcolor,
window =turtle.Screen()
window.bgcolor('blue')
EXAMPLE PROGRAM :

The “Default” Turtle :


 A “default” turtle is created when the setup method is called.
 The reference to this turtle object can be obtained by,
the_turtle = turtle.getturtle()
 A call to getturtle returns the reference to the default turtle and causes
it to appear on the screen.
 The initial position of all turtles is the center of the screen at
coordinate (0,0)
 The default turtle shape is an arrowhead.

Fundamental Turtle Attributes and Behavior :


 Turtle objects have three fundamental attributes:
position,
heading (orientation), and
pen attributes.

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 :

Turtle Heading and Relative Positioning:


A turtle’s position can be changed using relative positioning by use of
methods setheading , left, right, and forward.
A newly created turtle’s heading is to the right, at 0 degrees.
A turtle with heading
 90 degrees moves up;
 180 degrees moves left;
 270 degrees moves down.
A turtle’s heading can be changed by turning the turtle a given number
of degrees left, left(90), or right, right(90).
The forward method moves a turtle in the direction that it is currently
heading.
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

Additional Turtle Attributes :


The turtle is visible or not, the size (both demonstrated above), shape, and
fill color of the turtle, the turtle’s speed, and the tilt of the turtle.
Turtle Visibility:
Methods showturtle() and hideturtle() control a turtle’s visibility.

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')

Creating Multiple Turtles :


Any number of turtle objects can be created by use of method Turtle().
turtle1 = turtle.Turtle()
turtle2 = turtle.Turtle()
PROGRAM TO CREATE A TURTLE USING A POLYGON SHAPE :

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’)

This should be saved as simple.py

Modules and Namespaces :


• A namespace provides a context for a set of identifiers.
• Every module in Python has its own namespace.
• A name clash is when two otherwise distinct entities with the same
identifier become part of the same scope.
• Namespaces enable programs to avoid potential name clashes by
associating each identifier with the namespace from which it
originates.
• Name clashes can occur, for example, if two or more Python modules
contain identifiers with the same name and are imported into the
same program.

# mod1
def average(lst):
print('average of mod1 called')

# mod2
def average(lst):

print('average of mod2 called’)

import mod1, mod2

mod1.average(10,20,30)

mod2.average(10,20,30)

average(10,20,30)  creates an error – NAME CLASH

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))

Difference between the from modulename import and import modulename


forms of import in Python.:
When using import modulename , the namespace of the imported module
does not become part of the namespace of the importing module, as
mentioned. Therefore, identifiers of the imported module must be fully
qualified (e.g., modulename. func1) in the importing module. In contrast,
when using from-import, the imported module’s namespace becomes part of
the importing module’s namespace. Thus, imported identifiers are
referenced without being fully qualified (e.g., func1).

Module Private Variables :


• In Python, all the variables in a module are “public,” with the
convention that variables beginning with an two underscores are
intended to be private.
• Example:
def __f1():
Module Loading and Execution :
• Each imported module of a Python program needs to be located and
loaded into memory.
• Python first searches for modules in the current directory.
• If the module is not found, it searches the directories specified in the
PYTHONPATH environment variable.
• If the module is still not found (or PYTHONPATH is not defined), a
Python installation-specific path is searched (e.g., C:\Python32\Lib).
• If the program still does not find the module, an error (ImportError
exception) is reported.
• For our purposes, all of the modules of a program will be kept in the
same directory.
• When a module is loaded, a compiled version of the module with file
extension .pyc is automatically produced.
• Then, the next time that the module is imported, the compiled .pyc file
is loaded, rather than the .py fi le, to save the time of recompiling.
• A new compiled version of a module is automatically produced
whenever the compiled version is out of date with the source code
version of the module when loading, based on the dates that the files
were created/modified.
Built-in Function dir() :
• >>> dir()
['__builtins__', '__doc__', '__name__', '__package__’]
>>>import random
>>> n =10
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'n', 'random’]

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,

• reading from a fi le,

• writing to a fi le, and

• closing a fi le

Opening Text Files

• All files must first be opened before they can be used.

• In Python, when a file is opened, a file object is created that provides

methods for accessing the file.

Opening for Reading

• To open a fi le for reading, the built-in open function is used as shown,

input_fi le =open('myfi le.txt','r’)


• The first argument is the fi le name to be opened, 'myfi le.txt’.
• The second argument, 'r', indicates that the file is to be opened for
reading.
• If the fi le is successfully opened, a fi le object is created and assigned
to the provided identifier, in this case identifier input_fi le.
input_fi le =open('data/myfi le.txt',’r’)

• In this case, the fi le is searched for in a subdirectory called data of the


directory in which the program is contained. Thus, its location is
relative to the program location.

• Absolute paths can also be provided giving the location of a fi le


anywhere in the fi le system,

input_fi le=open('C:/mypythonfi les/data/myfi le.txt','r’)


• When the program has finished reading the fi le, it should be closed by
calling the close method on the file object,
input_fi le.close()

OPENING FOR WRITING


• To open a file for writing, the open function is used as shown below,
output_fi le =open('mynewfile.txt’, 'w’)
• 'w' is used to indicate that the file is to be opened for writing
• If the file already exists, it will be overwritten (starting with the first
line of the file).
• When using a second argument of 'a', the output will be appended to
an existing file instead.
• The only error that may occur is if the file system (such as the hard
disk) is full.
Reading Text Files
• The readline method returns as a string the next line of a text fi le,
including the end-of-line character, \n.
• When the end-of-fi le is reached, it returns an empty string.
• It is also possible to read the lines of a file by use of the for statement,
input_fi le = open('myfi le.txt','r’)
for line in input_fi le:
• Using a for statement, all lines of the file will be read one by one. Using
a while loop, however, lines can be read until a given value is found.
Writing Text Files
• The write method is used to write strings to a file
• In contrast to print when writing to the screen, the write method does
not add a newline character to the output string .
• Thus, a newline character will be output only if it is part of the string
being written.
• Finally, when writing to a file, data is first placed in an area of memory
called a buffer .
• Only when the buffer becomes full is the data actually written to the
file.
• This makes reading and writing fi les more efficient.
• Since the last lines written may not completely fill the buffer, the last
buffer’s worth of data may not be written.
The close() method flushes the buffer to force the buffer to be written to the
file.

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-Applicable Sequence Operations:

Because strings are immutable, sequence modifying operations do not


modify the string applied to. Rather, they construct new strings that are a
modified version of the original.
 The slice operator s[start:end] returns the substring starting with index
start, up to but not including index end.
 s.index(chr) returns the index of the first occurrence of chr in s
 min and max as applied to strings return the smallest (largest)
character based on the underlying Unicode encoding. Thus, for
example, all lowercase letters are larger (have a larger Unicode value)
than all uppercase letters.
EXAMPLES : s = 'Hello Goodbye!'
>>>len(s) >>>s.count('o') >>>s 1 '!!'
14 3 ‘Hello Goodbye!!!'

>>>s[6] >>> s.index('b') >>>min(s)


'G' 10 ''
>>>s[6:10] >>>'a' in s >>>max(s)
'Good' False 'y’

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.

Catching and Handling Exceptions:


Exceptions are caught and handled in Python by use of a try block and
exception handler.
Many of the functions in the Python Standard Library raise exceptions. For
example, the factorial function of the Python math module raises a
ValueError exception when a negative value is passed to it,
Any statement making a call (either directly or indirectly) to a function that
raises an exception causes the rest of the statements in the suite to be
skipped.
Exception Handling and User Input :
Programmer-defined functions may raise exceptions in addition to the
exceptions raised by the built-in functions of Python.
month = int(input('Enter current month (1–12): '))

Exception Handling and File Processing :


IOError exceptions raised as a result of a file open error can be caught and
handled
when opening a file for reading, an exception is raised if the file cannot be
found. In this case, the standard IOError exception is raised and the program
terminates with a 'No such file or directory' error message. We can catch this
exception and handle the error.
EXAMPLE :

******************THE END**********************

You might also like