ITPC 102 – Object-Oriented The LEGB Rule
Programming A useful way to remember how Python resolves
scope is with the LEGB rule. This rule is an
Lesson 8: Scope acronym for Local, Enclosing, Global, Built-in.
Scope Local (L): The local, or current, scope.
the area of program text within which it has Could be the body of a function or the top-
a particular value level scope of a script. Always represents
this value will be visible to some parts of a the scope that the Python interpreter is
program but not to others currently working in.
allows a single name to have different Enclosing (E): The enclosing scope. This is
meanings in different contexts the scope one level up from the local scope.
If the local scope is an inner function, the
enclosing scope is the scope of the outer
function. If the scope is a top-level function,
the enclosing scope is the same as the
global scope.
Global (G): The top-most scope in the
script. This contains all of the names defined
in the script that are not contained in a
function body.
The function “func()” has a different scope Built-in (B): Contains all of the names, such
than the code that exists outside of the as keywords, that are built-in to Python.
function. Functions such as round() and abs() are in
You can name an object inside func() the the built-in scope. Anything that you can use
same name as something outside func() and without first defining yourself is contained
Python can keep the two separated in the built-in scope.
The function body has what is known as a
local scope, with its own set of names
available to it. NOTE:
Code outside of the function body is in the
global scope - The use of the global keyword is considered
bad form in general.
Scope Resolution
Scopes have a hierarchy.
The inner_func() function is called an inner
function because it is defined inside of
another function.
Lesson 9: Modules Data Storage
Consider a module to be the same as a code Data (and programs) are loaded into primary
library. memory (RAM or Random Access Memory)
A file containing a set of functions you want for processing
to include in your application. From where?
The module can contain also variables of all o From input devices (keyboard,
types (arrays, dictionaries, objects etc.) microphone)
o From secondary memory - a hard
disk, a flash stick, a CD (Compact
Create a Module Disc), or a DVD (Digital Versatile
Disc)
To create a module just save the code you
want in a file with the file extension .py Primary and Secondary Storage
Example: Save this code in a file named
my_module.py
Use a Module
Import the module named my_module, and
call the greeting_student function:
What Is a File?
A file is a software object that allows a
program to represent and access data stored
in secondary memory
Naming a Module Two basic types of files:
You can create an alias when you import a Text files: for storing and accessing text
module, by using the as keyword: (characters)
Binary files: executable programs and their
data files (such as images, sound clips,
video)
Text Files
Import From Module
A text file is logically a sequence of
You can choose to import only parts from a characters
module, by using the from keyword. Basic operations are
o input (read characters from the
file)
o output (write characters to the file)
There are several flavors of each type of
operation
File Input
Lesson 10: Files
- We want to bring text in from a file for processing
Three steps:
Open the file for input
Read the text and save it in a variable
Process the text Extract a substring up to but not including
the last character (the newline)
This will produce an exact echo of the input
Opening a File file
<a flag> can be Using “readline”
a) ‘r’ - used for input, to read from an existing
file
b) ‘w’ - used for output, to overwrite an
existing file
c) ‘a’ - used for output, to append to an existing
file
The readline method reads a line of text
Example: Read Text from a File and returns it as a string, including the
newline character
This method returns the empty string if the
end of file is encountered
Count the Words
The file name must either be in the current
directory or be a pathname to a file in a
directory
Python raises an error if the file is not
found
“text” refers to one big string
Read Lines of Text from a File
File Output
- We want to save data to a text file
Four steps:
Open the file for output
The variable line picks up the next line of Covert the data to strings, if necessary
text on each pass through the loop Write the strings to the file
line will contain the newline character, so Close the file
the echo will print extra blank lines
Write Text to a File
The Try block lets you test a block of code
for errors.
The Except block lets you handle the error.
The Else block lets you execute code when
there is no error.
The Finally block lets you execute code,
regardless of the result of the try- and
If the file already exists, it is overwritten; except blocks.
otherwise, it is created in the current
directory or path
The write method expects a string as an
argument
Failure to close the file can result in losing
data
Write Integers to a File
Output: Variable x is not defined
Something else went wrong
write can be called 0 or more times
Data values must be converted to strings
before output
Separators, such as newlines or spaces, must
be explicitly written as well
Output: Hello
Sample Program
Nothing went wrong
Output: Something went wrong
The ‘try except’ is finished
Raise an exception
As a Python developer, you can choose to
throw an exception if a condition occurs.
To throw (or raise) an exception, use the
“raise” keyword.
Example
Lesson 11: Try-Except
Raise an error and stop the program if x is As problems get more interesting and
lower than 0: difficult, solutions (programs) become more
complex
How do we control this complexity, so as to
keep it manageable and not be overwhelmed
by it?
One Answer: Abstraction
Find a way of hiding complex details in a
new unit of code, thereby treating many
things as one thing.
Advantages of the raise keyword Examples:
It helps us raise exceptions when we may A function - hides an algorithm in a single
run into situations where execution can’t entity (math.sqrt, reply)
proceed. A module - hides a set of functions in a
It helps us reraise an exception that is single entity (random, math)
caught. A data structure - hides a collection of data
Raise allows us to throw one exception at in a single entity (list, dictionary)
any time.
It is useful when we want to work with input
validations. Using Abstractions
A program becomes a set of cooperating
modules, functions, and data structures
Exception Handling Each program component is simple enough
to be understood immediately and tested
independently
When interactions among components
become complex, package these in a new
abstraction (another function, data structure,
or module)
Not all useful abstractions are built in.
o You will sometimes need to custom
design an abstraction to suit the
needs of a specialized application or
suite of applications you are
developing.
Built-in Exceptions Another Abstraction: Objects
An object combines data and operations
https://docs.python.org/3/library/exceptions.
into a single unit
html (manually type in the link :p) An object is like an intelligent agent that
knows what to do with its own data
Examples:
o A GUI window
o A command button, a data entry
field, a drop-down menu
o A point, circle, rectangle, or polygon
o An image, a pixel, a sound clip, or a
network connection
o Actually, any Python data value
Lesson 12: Object-oriented Programming
(lists, strings, integers, etc.)
Organizing Programs
Closely study the relevant attributes and
behavior of the objects in the system being
Creating Objects from Classes modeled.
Design and code computational objects that
reflect these attributes and behavior
Example: Dice
Dice are used in many games of chance
(backgammon, monopoly, etc.)
A single die is a cube whose sides represent
the numbers 1-6
When a die is rolled, the number selected is
the one on the side that happens to be facing
Turtle, Point, and Circle are classes
up
myrtle, yertle, p, c1, and c2 refer to objects
or instances of these classes
A class defines the behavior of a set of
objects State and Behavior of a Die
The state of a die is the number currently
visible on its top face; its initial state is a
Getting Objects to Do Things randomly chosen number from 1 through 6
Behavior:
o Roll the die to reset its state to a
randomly chosen number from 1
through 6
o Get the die’s current number
Verbs in the description indicate
behavior; nouns indicate attributes (state)
We get an object to do things by running
methods
A method is like a function: it hides an The Die Class: External View
algorithm for performing a task
draw and getRadius are methods
Objects: State and Behavior
The set of a class’s methods is also called its
An object has two essential features: interface
1. A behavior - defined by the set of methods it The user of class only needs to know its
recognizes interface
2. A state - as defined by the data that it
contains
Using Some Dice
Object-oriented programming - uses
computational objects to model the state and
behavior of real-world objects
Modeling
Object Instantiation
Syntax of object instantiation:
Using a Checking Account
Calling a Method
Syntax of a method call:
Each Account Has Its Own State
Example: Checking Accounts
A checking account holds a balance
We can make deposits or withdrawals
Interest checking allows for a periodic
computation of interest, which is added to
the balance
The states of distinct objects can vary, but
the methods that apply to them are the same
State and Behavior of a Checking
Account
The state of an account is:
o The owner’ s name
o The owner’s PIN Object-oriented Programming: Summary
o The current balance Study the system of objects that you’re
The interest rate is common to all modeling to discover the relevant attributes
accounts and behavior
Behavior: For each type of object, choose a class
o Make a deposit of a given amount whose methods realize its behavior
o Make a withdrawal of a given Write a short tester program that creates
amount some objects and runs their methods
o Compute the interest Use the objects in your application
o Get the current balance
The Interface of the CheckingAccount Lesson 13: Classes and Objects
Class
Objects, Classes, and Methods
Every data value in Python is an object
Every object is an instance of a class
Built in classes include int, float, str, tuple,
list, dict
A class includes operations (methods) for
manipulating objects of that class (append,
Use
pop, sort, find, etc.)
Operators (== , [], in, +, etc.) are
“syntactic sugar” for methods
What Do Objects and Classes Do for Us?
An object bundles together data and
operations on those data
A computational object can model
practically any object in the real (natural or Specifying an Interface
artificial) world
The user of a class is only concerned with
Some classes come with a programming
learning the information included in the
language
headers of the class’s methods
Any others must be defined by the
This information includes the method
programmer
name and parameters
Collectively, this information comprises the
class’s interface
Programmer-Defined Classes Docstrings describe what the methods do
The EasyFrame class is used to create GUI
windows that are easy to set up
The Image class is used to load, process, Defining (Implementing) a Class
and save images
The definition or implementation of a class
Like the built-in classes, these classes
includes completed descriptions of an
include operations to run with their
object’s data and the methods for accessing
instances
and modifying those data
The data are contained in instance
variables and the methods are called
Other Examples instance methods
A Student class represents information Related class definitions often occur in the
about a student and her test scores same module
A Rational class represents rational
numbers and their operations
A Die class represents dice used in games Syntax Template for a Simple Class
SavingsAccount, CheckingAccount, Bank, Definition
and ATM are used to model a banking
system
Proton, Neutron, Electron, and Positron
model subatomic particles in nuclear
physics
Basically, a header followed by several method
definitions
The Die Class: Its Interface and Use Defining the Die Class
Interface
The name self must appear as the
first parameter in each instance
method definition
We’ll use random.randint to roll the die Python uses this parameter to refer to
the object on which the method is
called
The Class Header
Instance Variables
self must also be used with all instance
method calls and instance variable
references within the defining class
By convention, programmer-defined class
names are capitalized in Python
self refers to the current object (a die)
Built-in class names, like str, list, and
object, are not
Like built-in function names, built-in class Using Instance Variables
names appear in purple
All Python classes are subclasses of the
object class
A class can inherit behavior from its parent
class
The Class Docstring
self.value refers to this object’ s instance
variable
A class’s docstring describes the purpose of
the class
Accessing Data in an Object
Setting the Initial State
A method definition looks a bit like a
An object’s data can be viewed or accessed by
function definition
using its accessor methods
The __init__ method (also called a
constructor) is automatically run when an
object is instantiated; this method usually
sets the object’s initial state (d = Die())
The self Parameter The __str__ Method
As a rule of thumb, you should include an
__str__ method in each new class that you
define
Class Variables
An instance variable refers to storage
owned by a single instance
A class variable refers to storage owned by
the class, and thus available to all of its
instances
Encapsulation
Restricting the manipulation of an object’s
state by external users to a set of method
calls.
Polymorphism
Allowing several different classes to use the
same general method names.
Python supports this capability with
polymorphic methods.
The term polymorphic means “many
bodies,” and it applies to two methods that
have the same header but have different
definitions in different classes.
Inheritance
Inheritance allows us to define a class that
inherits all the methods and properties from
another class.
Parent class is the class being inherited
from, also called base class/superclass.
Child class is the class that inherits from
another class, also called derived
class/subclass.