Topics in Computer Science: Object-Oriented Programming
Topics in Computer Science: Object-Oriented Programming
History of Objects:
Where
they
came
from
undesirable rodents
Good programming = Procedural
Abstraction
Verb-oriented
Procedural
Abstractions
Define tasks to be performed
Break tasks into smaller and smaller
pieces
(modules" or "classes")
Write the code
Object-oriented
programming
First goal: Model the objects of the world
Noun-oriented
Focus on the domain of the program
Phases
Object-oriented analysis: Understand the
domain
implementation
Key ideas
Master-drawings in Sketchpad
Simulation objects in Simula
better
More robust, more maintainable, more
scalable
Birth of Objects, 1
of
Ivan2Sutherland's Sketchpad, 1963
Sketchpad
First object-oriented drawing program
Master and instance drawings
Draw a house
Make an instance
Add a chimney to the master
Poof! The instance grows a chimney
Other interesting features
1/3 Mile Square Canvas
Invention of rubber band lines
Simple animations
Birth of Objects, 2
of
2
Simula
Simulation programming language from
Norway, 1966
Define an activity which can be
instantiated as processes
Each process has it own data and
behavior
(Simulated) Multi-processing
Alan Kay
U. Utah PhD student in 1966
Read Sketchpad, Ported Simula
Saw objects as the future of
computer science
His dissertation: Flex, an objectoriented personal computer
A personal computer was a radical idea
then
medium
The first medium to
A 1970s depiction of
students
using an objectoriented system based
on Flex
Kays Insights
Computer as collection of Networked
Computers
All software is simulating the real world
Biology as model for objects
Bacterium has 120M of info, 1/500th of a
Birth of Objects
Objects as models of real world entities
Objects as Cells
Independent, indivisible, interactingin
standard ways
Scales well
Complexity: Distributed responsibility
Robustness: Independent
Supporting growth: Same mechanism everywhere
Reuse: Provide services, just like in real
world
A Dynabook is for
Learning
The Dynabook offers a new way to learn
new kinds of things
Dynamic systems (like evolution)
Smalltalk was
the programming
language
invented for
the Dynabook.
For the
Dynabook, WIMP
was invented:
overlapping Windows
Icons
Menus
mouse Pointer
Challenge
If you interacted with a computer
variables.
Heading, body color, pen color, X and Y position.
Yet each turtle can have its own values for these
fields.
Using Turtles in
Python
>>> makeWorld()
Adding a Turtle to
our
World
>>> earth
= makeWorld ()
>>> tina = makeTurtle(earth)
>>> print tina
No name turtle at 320, 240
heading 0.0.
>>> turtleX.setPenWidth
(100) # width of pen
>>> turtleX.setColor(blue)
>>> turtleX.turnRight ()
>>> turtleX.forward (300)
>>> turtleX.penUp () # dont
draw the path
>>> turtleX.setColor(red)
>>> turtleX.moveTo (400 ,0)
>>> turtleX.turnRight ()
>>> turtleX.setPenWidth
(160)
>>> turtleX.penDown () #
draw the path
>>> turtleX.forward (400)
Talking to turtles as
functions
or
We can tell a turtle to go forward by
calling a function (telling the function
messages/methods
to act on the turtle):
Challenge: What do
these
>>> earth = draw? >>> for steps
makeWorld()
>>> carol =
makeTurtle(earth)
>>> for steps in
range(4):
...
forward(carol,100)
...
turn(carol,90)
...
in
range(5):
...
forward(carol,100)
...
turn(carol,72)
...
Challenge
How would you draw a triangle?
Sending multiple
turtles messages
>>> sue =
makeTurtle(earth)
>>> tina.forward ()
>>> tina.turnRight ()
>>> tina.forward ()
position.
But each turtle has its own X and Y and
heading values.
Using
multipl
e
turtles
at once
def chase():
# Set up the four turtles
earth = World()
al = Turtle(earth)
bo = Turtle(earth)
cy = Turtle(earth)
di = Turtle(earth)
al.penUp()
al.moveTo(10,10)
al.penDown()
bo.penUp()
bo.moveTo(10,400)
bo.penDown()
cy.penUp()
cy.moveTo(400,10)
cy.penDown()
di.penUp()
di.moveTo(400,400)
di.penDown()
# Now, chase for 300 steps
for i in range(0,300):
chaseTurtle(al,cy)
chaseTurtle(cy,di)
chaseTurtle(di,bo)
chaseTurtle(bo,al)
Chasing
def
chaseTurtle(t1,t2):
t1.turnToFace(t2)
t1.forward(4)
Dropping pictures
from turtles
>>> # I chose Barbara.jpg
for this
>>>
p=makePicture(pickAFile()
)
>>> # Notice that we make
the World and Turtle here
>>> earth=World()
>>> turtle=Turtle(earth)
>>> turtle.drop(p)
def spinAPicture(apic):
canvas =
makeEmptyPicture(640,480)
ted = Turtle(canvas)
for i in range(0,360):
ted.drop(apic)
ted.forward(10)
ted.turn(20)
return canvas
Now SmartTurtle
instances understand
both how to
drawSquare() and
drawSquare(someWidth
)
Challenge
Write the method drawPolygon which
Inheritance and
Overriding
We can create a version of Turtle
thats confused.
Turns a random amount.
Goes forward a random amount.
Turtle.
It will override how to turn and go
forward.
ConfusedTurtle
import random
class ConfusedTurtle(Turtle):
def forward(self,num):
Turtle.forward(self,int(num*random.random
()))
def turn(self,num):
Turtle.turn(self,int(num*random.random())
)
Example on Making a
Class
from
Scratch:
Lets build a program to show a
SlideShow
show.
slide
It shows a picture.
Then plays a corresponding sound.
Slideshow
def playslideshow():
pic = makePicture(getMediaPath("barbara.jpg"))
snd = makeSound(getMediaPath("bassoon-c4.wav"))
show(pic)
blockingPlay(snd)
pic = makePicture(getMediaPath("beach.jpg"))
snd = makeSound(getMediaPath("bassoon-e4.wav"))
show(pic)
blockingPlay(snd)
pic = makePicture(getMediaPath("santa.jpg"))
snd = makeSound(getMediaPath("bassoon-g4.wav"))
show(pic)
blockingPlay(snd)
pic = makePicture(getMediaPath("jungle2.jpg"))
snd = makeSound(getMediaPath("bassoon-c4.wav"))
show(pic)
blockingPlay(snd)
Defining an object
Objects know things.
Data that is internal to the object.
We often call those instance variables.
Objects can do things.
Behavior that is internal to the object.
We call functions that are specific to an
object methods.
Classes
Objects are instances of classes in
and Python.
of an object.
A class defines what all instances of
We need to define a
slide
class
Easy enough:
class slide:
That wasnt so hard was it?
What comes next?
Some method for creating new slides.
Some method for playing slides.
Creating new
instances
We are going to create
new instances
by calling the class name as if it
were a function.
That will automatically create a new
Creating a slide
>>> slide1=slide()
>>> slide1.picture =
makePicture(getMediaPath("barbara.jpg")
)
>>> slide1.sound =
makeSound(getMediaPath("bassoonc4.wav"))
Defining a show()
method
To show a slide, we want to show()
the
picture and blockingPlay() the sound.
We define the function as part of the
class block.
So this is a def that gets indented.
object.method(),
Python finds the
method in the
objects class,
then calls it with
the object as an
input.
Python style is to
call that self.
def show(self):
show(self.picture)
blockingPlay(self.sound
)
Making it simpler
Can we get rid of those picture and
sound assignments?
What if we could call slide as if it
were a real function, with inputs?
Then we could pass in the picture and
calls a constructor.
A method that builds your object for
you.
underscore-underscore.
Its the predefined name for a method that
initializes new objects.
inputs:
The playslideshow()
def playslideshow():
slide1 = slide(getMediaPath("barbara.jpg"),
getMediaPath("bassoon-c4.wav"))
slide2 =
slide(getMediaPath("beach.jpg"),getMediaPath("bassoon
-e4.wav"))
slide3 =
slide(getMediaPath("santa.jpg"),getMediaPath("bassoon
-g4.wav"))
slide4 =
slide(getMediaPath("jungle2.jpg"),getMediaPath("basso
on-c4.wav"))
slide1.show()
slide2.show()
slide3.show()
slide4.show()
PlaySlideShow with
Map
def playslideshow():
slide1 = slide(getMediaPath("barbara.jpg"), getMediaPath("bassoonc4.wav"))
slide2 = slide(getMediaPath("beach.jpg"),getMediaPath("bassoone4.wav"))
slide3 = slide(getMediaPath("santa.jpg"),getMediaPath("bassoong4.wav"))
slide4 = slide(getMediaPath("jungle2.jpg"),getMediaPath("bassoonc4.wav"))
map(showSlide,[slide1,slide2,slide3,slide4])
instance variables?
By creating methods for getting (getters)
class slide:
def __init__(self,
pictureFile,soundFile):
Class
with
getters
and
setters
self.setPicture(makePicture(pictureFile))
self.setSound(makeSound(soundFile))
def getPicture(self):
return self.picture
def getSound(self):
return self.sound
def setPicture(self,newPicture):
self.picture = newPicture
def setSound(self,newSound):
self.sound = newSound
def show(self):
show(self.getPicture())
blockingPlay(self.getSound())
Challenge
Write a version of this function where
is powerful.
everywhere.
Pictures, sounds, samples, colors
these are all objects.
Weve been doing aggregation.
Weve worked with or talked about lists
Using picture as an
object
>>> pic=makePicture(getMediaPath("barbara.jpg"))
>>> pic.show()
the programmer.
You dont need to know exactly what method
is being executed.
You dont even need to know exactly what
object it is that youre telling to show()
You just know your goal: Show this object!
Uncovering the
objects
This is how the show() function
is
defined in JES:
You can ignore the raise and if
The key point is that the function is
We can get/set
components
at
either
getRed, getBlue, getGreen, setRed,
setBlue, setGreen
level
Are all defined for both colors and pixels
Overview of graphics
methods
pic.addRect(color,x,y,width,height)
pic.addRectFilled(color,x,y,width,heig
ht)
pic.addOval(color,x,y,width,height)
pic.addOvalFilled(color,x,y,width,heig
ht)
Arcs
pic.addArc(color,x,y,width,height,startang
le,arcangle)
pic.addArcFilled(color,x,y,width,height,st
artangle,arcangle)
Make an arc for arcangle degrees, where
Text
Text can have style, but only limited.
Java limits it for cross-platform
compatibility.
pic.addText(color,x,y,string)
pic.addTextWithStyle(color,x,y,string,style
)
Style is made by makeStyle(font,emph,size)
Font is sansSerif, serf, or mono
Emph is italic, bold, or plain.
Rectangles: Coloring
lines and fills
>>> pic=makePicture
(getMediaPath("640x480.jpg"
))
>>> pic.addRectFilled
(orange,10,10,100,100)
>>> pic.addRect
(blue,200,200,50,50)
>>> pic.show()
>>>
pic.writeTo("newrects.jpg")
Ovals
>>> pic=makePicture
(getMediaPath("640x480.
jpg"))
>>> pic.addOval
(green,200,200,50,50)
>>> pic.addOvalFilled
(magenta,10,10,100,100)
>>> pic.show()
>>>
pic.writeTo("ovals.jpg"
)
>>> pic=makePicture
(getMediaPath("640x480.jpg"))
>>>
pic.addArc(red,10,10,100,100,
5,45)
>>> pic.show()
>>> pic.addArcFilled
(green,200,100,200,100,1,90)
>>> pic.repaint()
>>>
pic.addLine(blue,400,400,600,
400)
>>> pic.repaint()
>>> pic.writeTo("arcslines.jpg")
Text examples
>>> pic=makePicture
(getMediaPath("640x480.jpg"))
>>>
pic.addText(red,10,100,"This
is a red string!")
>>> pic.addTextWithStyle
(green,10,200,"This is a
bold, italic, green, large
string",
makeStyle(sansSerif,bold+ital
ic,18))
>>> pic.addTextWithStyle
(blue,10,300,"This is a blue,
larger, italic-only, serif
string",
makeStyle(serif,italic,24))
>>> pic.writeTo("text.jpg")
Backwards using
methods
def backwards(filename):
source = makeSound(filename)
target = makeSound(filename)
return target
Why objects?
An important role for objects is to reduce the
behavior together.
Think about changing the name of an instance
Combining objects
was not
objects.
languages.
In Java or Smalltalk, instance variables
Inheritance
We can declare one class to be inherited by
another class.
It provides instant polymorphism.
The child class immediately gets all the data
class had.
This is called making the child a
class rectangle3D(rectangle):
Inheritance is a
tradeoff
Inheritance is talked about a
lot in
of code.
If you have two classes that will have
many the same methods, then set up
inheritance.
sounds.
Behavior that you want to define over
that group.