Title: Computer Science 111
1Computer Science 111
- Fundamentals of Programming I
- Introduction to Programmer-Defined Classes
2Objects, 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 include operations (methods) for
manipulating objects of that class (append, pop,
sort, find, etc.) - Operators (, , in, etc.) are syntactic
sugar for methods
3What 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 artificial) world - Some classes come with a programming language
- Any others must be defined by the programmer
4Programmer-Defined Classes
- The Turtle class is used to create objects that
can draw pictures in a graphics window - The Image class is used to load, process, and
save images - Like the built-in classes, these classes include
operations to run with their instances
5Other Examples
- A Student class represents information about a
student and her test scores - A Rational class represents rational numbers and
their operations - A Die class represents dice used in games
- SavingsAccount, CheckingAccount, Bank, and ATM
are used to model a banking system - Proton, Neutron, Electron, and Positron model
particles in nuclear physics
6The Die Class Its Interface and Use
Interface
die.py The module for the Die
class Die() Returns a new Die object roll()
Resets the die's value getValue()
Returns the die's value
7The Die Class Its Interface and Use
Interface
die.py The module for the Die
class Die() Returns a new Die object roll()
Resets the die's value getValue()
Returns the die's value
Use
from die import Die d Die()
Create a new Die object d.roll()
Roll it print(d.getValue()) Display its
value help(Die) Look up the
documentation
8Specifying an Interface
- The user of a class is only concerned with
learning the information included in the headers
of the classs methods - This information includes the method name and
parameters - Collectively, this information comprises the
classs interface - Docstrings describe what the methods do
9Defining (Implementing) a Class
- The definition or implementation of a class
includes completed descriptions of an objects
data and the methods for accessing and modifying
those data - The data are contained in instance variables and
the methods are called instance methods - Related class definitions often occur in the same
module
10Syntax Template for a Simple Class Definition
ltdocstring for the modulegt ltimports of other
modules usedgt class ltidentifiergt(ltparent
classgt) ltdocstring for the classgt
ltmethod definitionsgt
Basically a header followed by several method
definitions
11Defining the Die Class
from random import randint class
ltidentifiergt(ltparent classgt) ltdocstring for
the classgt ltmethod definitionsgt
Well use random.randint to roll the die
12The Class Header
from random import randint class Die(object)
ltdocstring for the classgt ltmethod
definitionsgt
By convention, class names are capitalized in
Python
13The Class Header
from random import randint class Die(object)
ltdocstring for the classgt ltmethod
definitionsgt
All Python classes are subclasses of the object
class A class can inherit behavior from its
parent class
14The Class Docstring
from random import randint class Die(object)
"""This class represents a six-sided die."""
ltmethod definitionsgt
A classs docstring describes the purpose of the
class
15Setting the Initial State
from random import randint class Die(object)
"""This class represents a six-sided die."""
def __init__(self) self._value 1
A method definition looks a bit like a function
definition The __init__ method (also called a
constructor) is automatically run when an object
is instantiated this method usually sets the
objects initial state (d Die())
16The self Parameter
from random import randint class Die(object)
"""This class represents a six-sided die."""
def __init__(self) self._value 1
The name self must appear as the first parameter
in each instance method definition Python uses
this parameter to refer to the object on which
the method is called
17Instance Variables
from random import randint class Die(object)
"""This class represents a six-sided die."""
def __init__(self) self._value 1
self must also be used with all instance method
calls and instance variable references within the
defining class self refers to the current object
(a die)
18Using Instance Variables
from random import randint class Die(object)
"""This class represents a six-sided die."""
def __init__(self) self._value 1
def roll(self) """Resets the die's
value.""" self._value randint(1, 6)
def getValue(self) return self._value
self._value refers to this objects instance
variable
19Where Are Classes Defined?
- Like everything else, in a module
- Define the Die class in a die module
- Related classes usually go in the same module
(SavingsAccount and Bank the bank module)
20The Interface of the SavingsAccount Class
SavingsAccount(name, pin, bal) Returns a new
object getBalance() Returns the
current balance deposit(amount)
Makes a deposit withdraw(amount)
Makes a withdrawal computeInterest()
Computes the interest and
deposits it
21Defining the SavingsAccount Class
class SavingsAccount(object) """This class
represents a savings account.""" def
__init__(self, name, pin, balance 0.0)
self._name name self._pin pin
self._balance balance Other methods go
here
Note that name is a methods parameter, whereas
self._name is an objects instance variable
22The Lifetime of a Variable
class SavingsAccount(object) """This class
represents a savings account.""" def
__init__(self, name, pin, balance 0.0)
self._name name self._pin pin
self._balance balance Other methods go
here
Parameters exist only during the lifetime of a
method call, whereas instance variables exist for
the lifetime of an object
23Parameters or Instance Variables?
- Use a parameter to send information through a
method to an object - Use an instance variable to retain information in
an object - An objects state is defined by the current
values of all of its instance variables - References to instance variables must include the
qualifier self
24The Scope of a Variable
- The scope of a variable is the area of program
text within which its value is visible - The scope of a parameter is the text of its
enclosing function or method - The scope of an instance variable is the text of
the enclosing class definition (perhaps many
methods)
25The Scope of a Variable
class SavingsAccount(object) """This class
represents a savings account.""" def
__init__(self, name, pin, balance 0.0)
self._name name self._pin pin
self._balance balance def deposit(self,
amount) self._balance amount def
withdraw(self, amount) self._balance -
amount
self._balance always refers to the same storage
area (for one object) amount refers to a
different storage area for each method call
26For Friday