Python Classes and Objects
Python Classes and Objects
Python Classes and Objects
Objects
A Basic Introduction
• Generally represent:
– tangible entities (e.g., student, airline ticket, etc.)
– intangible entities (e.g., data stream)
Attributes:
- location, radius,color
Methods:
- draw, move
objects/CircleModule.py
Constructors
• The objcet’s constructor method is named __init__
• The values of the instance variables define the state of the individual
object
– myCircle.myFunction(actualP1, actualP2)
Not this
• is like calling:
– Circle.myFunction(myCircle,actualP1, actualP2)
• “self” really gets the value of “myCircle”.. but
it happens automatically!
Why use classes at all?
• Classes and objects are more like the real
world. They minimize the semantic gap by
modeling the real world more closely
Public
Interface
?
You know the public
interface. Do you know
implementation details?
Do you care?
As long as the public interface stays the
same, you don’t care about
implementation changes
Implementing Public/Private Interfaces
What if I want to store the name instead as first and last name in the class?
Well, with the getter I only have to do this:
def getName(self):
return self.firstname + self.lastname
If I had used dot notation outside the class, then all the code OUTSIDE the
class would need to be changed because the internal structure INSIDE the
class changed. Think about libraries of code… If the Python-authors change
how the Button class works, do you want to have to change YOUR code?
No! Encapsulation helps make that happen. They can change anything
inside they want, and as long as they don’t change the method signatures,
your code will work fine.
Why? Same reason + one more. I want to hide the internal structure of my
Class, so I want people to go through my methods to get and set instance
variables. What if I wanted to start storing people’s ages in dog-years?
Easy with setters:
def setAge(self, age):
self.age = age / 7
More commonly, what if I want to add validation… for example, no age can
be over 200 or below 0? If people use dot notation, I cannot do it. With
setters:
def setAge(self, age):
if age > 200 or age < 0:
# show error
else:
self.age = age / 7
Getters and Setters
def __str__(self):
return "Name is:"+ self.__name
Name is:KarlJohnson
• See BouncingBall Slides.
Data Processing with Class
• A class is useful for modeling a real-world
object with complex behavior.
• Another common use for objects is to group
together a set of information that describes a
person or thing.
– Eg., a company needs to keep track of information
about employees (an Employee class with
information such as employee’s name, social
security number, address, salary, etc.)
Data Processing with Class
• Grouping information like this is often
called a record.
• Let’s try a simple data processing
example!
• A typical university measures courses in
terms of credit hours, and grade point
averages are calculated on a 4 point
scale where an “A” is 4 points, a “B” is
three, etc.
Data Processing with Class
• Grade point averages are generally
computed using quality points. If a class
is worth 3 credit hours and the student
gets an “A”, then he or she earns
3(4) = 12 quality points. To calculate the
GPA, we divide the total quality points
by the number of credit hours
completed.
Data Processing with Class
• Suppose we have a data file that
contains student grade information.
• Each line of the file consists of a
student’s name, credit-hours, and
quality points.
Adams, Henry 127 228
Comptewell, Susan 100 400
DibbleBit, Denny 18 41.5
Jones, Jim 48.5 155
Smith, Frank 37 125.33
Data Processing with Class
• Our job is to write a program that reads
this file to find the student with the best
GPA and print out their name, credit-
hours, and GPA.
• The place to start? Creating a Student
class!
• We can use a Student object to store
this information as instance variables.
Data Processing with Class
• class Student:
def __init__(self, name, hours, qpoints):
self.name = name
self.hours = float(hours)
self.qpoints = float(qpoints)
• The values for hours are converted to
float to handle parameters that may be
floats, ints, or strings.
• To create a student record:
aStudent = Student(“Adams, Henry”, 127, 228)
• The coolest thing is that we can store all the
information about a student in a single
variable!
Data Processing with Class
• We need to be able to access this information, so we
need to define a set of accessor methods.
• def getName(self):
return self.name
def getHours(self): These are commonly
return self.hours
called “getters”
def getQPoints(self):
return self.qpoints
def gpa(self):
return self.qpoints/self.hours
• For example, to print a student’s name you could
write:
print aStudent.getName()
• aStudent.name
Data Processing with Class
• How can we use these tools to find the
student with the best GPA?
• We can use an algorithm similar to
finding the max of n numbers! We could
look through the list one by one,
keeping track of the best student seen
so far!
Data Processing with Class
Pseudocode:
Get the file name from the user
Open the file for reading
Set best to be the first student
For each student s in the file
if s.gpa() > best.gpa
set best to s
Print out information about best
Data Processing with Class
# gpa.py def main():
# Program to find student with highest GPA filename = raw_input("Enter name the grade file: ")
import string infile = open(filename, 'r')
best = makeStudent(infile.readline())
class Student: for line in infile:
s = makeStudent(line)
def __init__(self, name, hours, qpoints): if s.gpa() > best.gpa():
self.name = name best = s
self.hours = float(hours) infile.close()
self.qpoints = float(qpoints) print "The best student is:", best.getName()
print "hours:", best.getHours()
def getName(self): print "GPA:", best.gpa()
return self.name
if __name__ == '__main__':
def getHours(self): main()
return self.hours
def getQPoints(self):
return self.qpoints
def gpa(self):
return self.qpoints/self.hours
def makeStudent(infoStr):
name, hours, qpoints = string.split(infoStr,"\t")
return Student(name, hours, qpoints)
Helping other people use your classes
random(...)
random() -> x in the interval [0, 1).
Module Documentation
• To see the documentation for an entire
module, try typing help(module_name)!
• The following code for the projectile
class has docstrings.
Module Documentation
# projectile.py
"""projectile.py
Provides a simple class for modeling the flight of projectiles."""
class Projectile:
def getY(self):
"Returns the y position (height) of this projectile."
return self.ypos
def getX(self):
"Returns the x position (distance) of this projectile."
return self.xpos
PyDoc
• PyDoc The pydoc module automatically
generates documentation from Python
modules. The documentation can be
presented as pages of text on the
console, served to a Web browser, or
saved to HTML files.