Скачать презентацию Introduction to Computing and Programming in Python A Скачать презентацию Introduction to Computing and Programming in Python A

3230cfa1dc40f11df771b3844536bde4.ppt

  • Количество слайдов: 91

Introduction to Computing and Programming in Python: A Multimedia Approach 4 ed Chapter 17: Introduction to Computing and Programming in Python: A Multimedia Approach 4 ed Chapter 17: Topics in Computer Science: Object-Oriented Programming

Chapter Objectives Chapter Objectives

History of Objects: Where they came from Start of the Story: Late 60's and History of Objects: Where they came from Start of the Story: Late 60's and Early 70's Windows are made of glass, mice are undesirable rodents Good programming = Procedural Abstraction Verb-oriented

Procedural Abstractions Define tasks to be performed Break tasks into smaller and smaller pieces Procedural Abstractions Define tasks to be performed Break tasks into smaller and smaller pieces Until you reach an implementable size Define the data to be manipulated Design how functions interact What's the input What's the output Group functions into components (“modules" or "classes") Write the code

Object-oriented programming First goal: Model the objects of the world Noun-oriented Focus on the 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 Define an object-based model of it Object-oriented design: Define an implementation Design the solution Object-oriented programming: Build it

How'd we get from there to here? Key ideas Master-drawings in Sketchpad Simulation “objects” How'd we get from there to here? Key ideas Master-drawings in Sketchpad Simulation “objects” in Simula Alan Kay and a desire to make software better More robust, more maintainable, more scalable

Birth of Objects, 1 of 2 Ivan Sutherland's Sketchpad, 1963 Birth of Objects, 1 of 2 Ivan Sutherland's Sketchpad, 1963

Sketchpad First object-oriented drawing program Master and instance drawings Draw a house Make an 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 Simulation programming language from Norway, 1966 Define an Birth of Objects, 2 of 2 Simulation programming language from Norway, 1966 Define an activity which can be instantiated as processes Each process has it own data and behavior In real world, objects don't mess with each others' internals directly (Simulated) Multi-processing No Universal Scheduler in the Real World

Alan Kay U. Utah Ph. D student in 1966 Read Sketchpad, Ported Simula Saw Alan Kay U. Utah Ph. D student in 1966 Read Sketchpad, Ported Simula Saw “objects” as the future of computer science His dissertation: Flex, an object-oriented personal computer A personal computer was a radical idea then

"A Personal Computer for Children of All Ages" Flex, an object-oriented personal computer Enabled by Moore's Law Imagining personal computing in 1969 Computer as metamedium The first medium to encompass other media A 1970's depiction of students using an object-oriented system based on Flex

Kay's Insights “Computer” as collection of Networked Computers All software is simulating the real Kay's Insights “Computer” as collection of Networked Computers All software is simulating the real world Biology as model for objects Bacterium has 120 M of info, 1/500 th of a Cell, and we have 1013 of these in us. Talk about processing power! Talk about managing complexity! What man-made things can scale like that? Stick a million dog houses together to get the Empire State Building?

Birth of Objects as models of real world entities Objects as Cells Independent, indivisible, Birth of Objects as models of real world entities Objects as Cells Independent, indivisible, interacting—in standard ways Scales well Complexity: Distributed responsibility Robustness: Independent Supporting growth: Same mechanism everywhere Reuse: Provide services, just like in real world

Alan Kay's Dynabook (1972) Alan Kay sees the Computer as Man's first metamedium A Alan Kay's Dynabook (1972) Alan Kay sees the Computer as Man's first metamedium A medium that can represent any other media: Animation, graphics, sound, photography, etc. Programming is yet another medium The Dynabook is a (yet mythical) computer for creative metamedia exploration and reading Handheld, wireless network connection Writing (typing), drawing and painting, sound recording, music composition and synthesis End-user programming

Prototype Dynabook (Xerox PARC Learning Research Group) Prototype Dynabook (Xerox PARC Learning Research Group)

A Dynabook is for Learning The Dynabook offers a new way to learn new A Dynabook is for Learning The Dynabook offers a new way to learn new kinds of things Dynamic systems (like evolution) Especially decentralized ones (Resnick, 1992) Knowledge representation (Papert, 1980) Programming (Kay & Goldberg, 1977) But need a system for creative expression In a time when “windows” were made of glass, and “mice” were undesirable rodents

Smalltalk-72 Smalltalk was the programming language invented for the Dynabook. For the Dynabook, WIMP Smalltalk-72 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 through a terminal (as opposed to punched Challenge If you interacted with a computer through a terminal (as opposed to punched cards) before Smalltalk-72, what do you think you did to get the computer to do something for you?

A first Object: Logo Turtle Dr. Seymour Papert at MIT invented the Turtle as A first Object: Logo Turtle Dr. Seymour Papert at MIT invented the Turtle as a graphical and mathematical object to think with for the children's programming language, Logo A turtle is an object. Every turtle understands the same methods. Every turtle has the same fields or instance 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 >>> make. World() Using Turtles in Python >>> make. World()

Adding a Turtle to our World >>> earth = make. World () >>> tina Adding a Turtle to our World >>> earth = make. World () >>> tina = make. Turtle(earth) >>> print tina No name turtle at 320, 240 heading 0. 0.

Things turtles can do: Try it! >>> turtle. X. pen. Up () >>> turtle. Things turtles can do: Try it! >>> turtle. X. pen. Up () >>> turtle. X. move. To (0, 0) >>> turtle. X. pen. Down () >>> turtle. X. move. To (639 , 479) >>> world. X = make. World () >>> turtle. X = make. Turtle(world. X) >>> turtle. X. set. Visible(false) #don't draw the turtle >>> turtle. X. pen. Up () # don't draw the path >>> turtle. X. move. To (0 , 240) >>> turtle. X. pen. Down () # draw the path >>> turtle. X. set. Pen. Width (100) # width of pen >>> turtle. X. set. Color(blue) >>> turtle. X. turn. Right () >>> turtle. X. forward (300) >>> turtle. X. pen. Up () # don't draw the path >>> turtle. X. set. Color(red) >>> turtle. X. move. To (400 , 0) >>> turtle. X. turn. Right () >>> turtle. X. set. Pen. Width (160) >>> turtle. X. pen. Down () # draw the path >>> turtle. X. forward (400)

Talking to turtles as functions or messages/methods We can tell a turtle to go Talking to turtles as functions or messages/methods We can tell a turtle to go forward by calling a function (telling the function to act on the turtle): Or we can ask Tina to go forward, a certain amount. We are sending a message to Tina, asking her to execute a function that only turtles know: A “method”

Challenge: What do these draw? >>> earth = make. World() >>> carol = make. Challenge: What do these draw? >>> earth = make. World() >>> carol = make. Turtle(earth) >>> for steps in range(4): . . . forward(carol, 100). . . turn(carol, 90). . . >>> for steps in range(5): . . . forward(carol, 100). . . turn(carol, 72). . .

Challenge How would you draw a triangle? Challenge How would you draw a triangle?

Sending multiple turtles messages >>> sue = make. Turtle(earth) >>> tina. forward () >>> Sending multiple turtles messages >>> sue = make. Turtle(earth) >>> tina. forward () >>> tina. turn. Right () >>> tina. forward () Sue stays put while Tina moves. These are objects on which we execute methods.

Each turtle knows the same things, has the same state Each turtle knows how Each turtle knows the same things, has the same state Each turtle knows how to go forward and turn. Each knows a heading and an X and Y position. But each turtle has its own X and Y and heading values.

Using multiple turtles at once def chase(): # Set up the four turtles earth Using multiple 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. pen. Up() al. move. To(10, 10) al. pen. Down() bo. pen. Up() bo. move. To(10, 400) bo. pen. Down() cy. pen. Up() cy. move. To(400, 10) cy. pen. Down() di. pen. Up() di. move. To(400, 400) di. pen. Down() # Now, chase for 300 steps for i in range(0, 300): chase. Turtle(al, cy) chase. Turtle(cy, di) chase. Turtle(di, bo) chase. Turtle(bo, al)

Chasing def chase. Turtle(t 1, t 2): t 1. turn. To. Face(t 2) t Chasing def chase. Turtle(t 1, t 2): t 1. turn. To. Face(t 2) t 1. forward(4)

What four turtles chasing each other looks like What four turtles chasing each other looks like

 What shape does this draw? (1) A square with sides of 200 (2) What shape does this draw? (1) A square with sides of 200 (2) A set of spikes (3) A circle (4) Error – you can’t have 600 turtles.

Dropping pictures from turtles >>> # I chose Barbara. jpg for this >>> p=make. Dropping pictures from turtles >>> # I chose Barbara. jpg for this >>> p=make. Picture(pick. AFile()) >>> # Notice that we make the World and Turtle here >>> earth=World() >>> turtle=Turtle(earth) >>> turtle. drop(p)

Spinning and dropping a turtle on a canvas def spin. APicture(apic): canvas = make. Spinning and dropping a turtle on a canvas def spin. APicture(apic): canvas = make. Empty. Picture(640, 480) ted = Turtle(canvas) for i in range(0, 360): ted. drop(apic) ted. forward(10) ted. turn(20) return canvas

Teaching Turtles new Tricks class Smart. Turtle(Turtle ): def draw. Square(self ): for i Teaching Turtles new Tricks class Smart. Turtle(Turtle ): def draw. Square(self ): for i in range (0 , 4): self. turn. Right () self. forward () The class Turtle exists. Here, we create a new kind of Turtle, a specialization called Smart. Turtle, that knows how to draw squares. draw. Square is a method that Smart. Turtle instances understand. All Python methods must accept self as the first parameter—self is the object receiving the message.

Trying our new method >>> earth = World () >>> smarty = Smart. Turtle(earth) Trying our new method >>> earth = World () >>> smarty = Smart. Turtle(earth) >>> smarty. draw. Square ()

More than one method class Smart. Turtle(Turtle ): def draw. Square(self , width=100 ): More than one method class Smart. Turtle(Turtle ): def draw. Square(self , width=100 ): for i in range (0 , 4): self. turn. Right () self. forward(width) Now Smart. Turtle instances understand both how to draw. Square() and draw. Square(some. Width) >>> mars = World () >>> tina = Smart. Turtle(mars) >>> tina. draw. Square(30) >>> tina. draw. Square(150) >>> tina. draw. Square(100) >>> # Does the same thing >>> tina. draw. Square()

Trying the new methods >>> mars = World () >>> tina = Smart. Turtle(mars) Trying the new methods >>> mars = World () >>> tina = Smart. Turtle(mars) >>> tina. draw. Square (30) >>> tina. draw. Square (150) >>> tina. draw. Square (100)

Challenge Write the method draw. Polygon which takes a size and number of sides. Challenge Write the method draw. Polygon which takes a size and number of sides.

Inheritance and Overriding We can create a version of Turtle that's “confused. ” Turns Inheritance and Overriding We can create a version of Turtle that's “confused. ” Turns a random amount. Goes forward a random amount. This class is a subclass of Turtle. That means it inherits everything from Turtle. It will override how to turn and go forward.

Confused. Turtle import random class Confused. Turtle(Turtle): def forward(self, num): Turtle. forward(self, int(num*random())) def Confused. Turtle import random class Confused. Turtle(Turtle): def forward(self, num): Turtle. forward(self, int(num*random())) def turn(self, num): Turtle. turn(self, int(num*random()))

Works the same, performs different >>> pluto = World() >>> goofy = Confused. Turtle(pluto) Works the same, performs different >>> pluto = World() >>> goofy = Confused. Turtle(pluto) >>> goofy. forward(100) >>> goofy. turn(90)

Combining recursion with turtles Start from this: def triangle(turtle , size): for sides in Combining recursion with turtles Start from this: def triangle(turtle , size): for sides in range (3): forward(turtle , size) turn(turtle , 120)

Recurse before moving def nested. Tri(t, size): if size < 10: return for sides Recurse before moving def nested. Tri(t, size): if size < 10: return for sides in range(3): nested. Tri(t, size/2) forward(t, size) turn(t, 120)

Recurse in the corners def corner. Tri(t, size): if size < 10: return for Recurse in the corners def corner. Tri(t, size): if size < 10: return for sides in range(3): forward(t, size) corner. Tri(t, size/2) turn(t, 120)

Example on Making a Class from Scratch: Slide. Show Let's build a program to Example on Making a Class from Scratch: Slide. Show Let's build a program to show a slide show. It shows a picture. Then plays a corresponding sound. We'll use the introduced-but-never-used blocking. Play() to make the execution wait until the sound is done.

Slideshow def playslideshow(): pic = make. Picture(get. Media. Path( Slideshow def playslideshow(): pic = make. Picture(get. Media. Path("barbara. jpg")) snd = make. Sound(get. Media. Path("bassoon-c 4. wav")) show(pic) blocking. Play(snd) pic = make. Picture(get. Media. Path("beach. jpg")) snd = make. Sound(get. Media. Path("bassoon-e 4. wav")) show(pic) blocking. Play(snd) pic = make. Picture(get. Media. Path("santa. jpg")) snd = make. Sound(get. Media. Path("bassoon-g 4. wav")) show(pic) blocking. Play(snd) pic = make. Picture(get. Media. Path("jungle 2. jpg")) snd = make. Sound(get. Media. Path("bassoon-c 4. wav")) show(pic) blocking. Play(snd)

What's wrong with this? From Procedural Abstraction: We have duplicated code. We should get What's wrong with this? From Procedural Abstraction: We have duplicated code. We should get rid of it. From Object-Oriented Programming: We have an object: A slide.

Defining an object Objects know things. Data that is internal to the object. We 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. But you knew that one already. We access both of these using dot notation object. variable object. method()

The Slide Object What does a slide know? It has a picture. It has The Slide Object What does a slide know? It has a picture. It has a sound What can a slide do? Show itself. Show its picture. (Blocking) Play its sound.

Classes Objects are instances of classes in many objectoriented languages. Including Smalltalk, Java. Script, Classes Objects are instances of classes in many objectoriented languages. Including Smalltalk, Java. Script, and Python. A class defines the data and behavior of an object. A class defines what all instances of that class know and can do.

We need to define a slide class Easy enough: class slide: That wasn't so We need to define a slide class Easy enough: class slide: That wasn't 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 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 instance of the class.

Creating a slide Let's create a slide and give it a picture and sound Creating a slide Let's create a slide and give it a picture and sound instance variables. >>> slide 1=slide() >>> slide 1. picture = make. Picture(get. Media. Path("barbara. jpg")) >>> slide 1. sound = make. Sound(get. Media. Path("bassoonc 4. wav"))

Defining a show() method To show a slide, we want to show() the picture Defining a show() method To show a slide, we want to show() the picture and blocking. Play() the sound. We define the function as part of the class block. So this is a def that gets indented.

Defining the method show() Why self? When we say object. method(), Python finds the Defining the method show() Why self? When we say object. method(), Python finds the method in the object's class, then calls it with the object as an input. Python style is to call that self. It's the object itself. class slide: def show(self): show(self. picture) blocking. Play(self. sound)

Now we can show our slide >>> slide 1. show() We execute the method Now we can show our slide >>> slide 1. show() We execute the method using the same dot notation we've seen previously. Does just what you'd expect it to do. Shows the picture. Plays the sound.

Making it simpler Can we get rid of those picture and sound assignments? What 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 sound filenames as inputs. We can do this, by defining what Java calls a constructor. A method that builds your object for you.

Making instances more flexibly To create new instances with inputs, we must define a Making instances more flexibly To create new instances with inputs, we must define a function named __init__ That's underscore-i-n-i-t-underscore. It's the predefined name for a method that initializes new objects. Our __init__ function will take three inputs: self, because all methods take that. And a picture and sound filename. We'll create the pictures and sounds in the method.

Our whole slide class slide: def __init__(self, picture. File, sound. File): self. picture = Our whole slide class slide: def __init__(self, picture. File, sound. File): self. picture = make. Picture(picture. File) self. sound = make. Sound(sound. File) def show(self): show(self. picture) blocking. Play(self. sound)

The playslideshow() def playslideshow(): slide 1 = slide(get. Media. Path( The playslideshow() def playslideshow(): slide 1 = slide(get. Media. Path("barbara. jpg"), get. Media. Path("bassoonc 4. wav")) slide 2 = slide(get. Media. Path("beach. jpg"), get. Media. Path("bassoone 4. wav")) slide 3 = slide(get. Media. Path("santa. jpg"), get. Media. Path("bassoong 4. wav")) slide 4 = slide(get. Media. Path("jungle 2. jpg"), get. Media. Path("bassoonc 4. wav")) slide 1. show() slide 2. show() slide 3. show() slide 4. show()

Using map with slides Slides are now just objects, like any other kind of Using map with slides Slides are now just objects, like any other kind of object in Python. They can be in lists, for example. Which means that we can use map. We need a function: def show. Slide(aslide): aslide. show()

Play. Slide. Show with Map def playslideshow(): slide 1 = slide(get. Media. Path( Play. Slide. Show with Map def playslideshow(): slide 1 = slide(get. Media. Path("barbara. jpg"), get. Media. Path("bassoon-c 4. wav")) slide 2 = slide(get. Media. Path("beach. jpg"), get. Media. Path("bassoon-e 4. wav")) slide 3 = slide(get. Media. Path("santa. jpg"), get. Media. Path("bassoon-g 4. wav")) slide 4 = slide(get. Media. Path("jungle 2. jpg"), get. Media. Path("bassoon-c 4. wav")) map(show. Slide, [slide 1, slide 2, slide 3, slide 4])

But not very “object-oriented” This version of the slide object is not very object But not very “object-oriented” This version of the slide object is not very object oriented. We set the picture and sound by directly touching the instance variables. Adele Goldberg, who helped invent the first programming language Smalltalk, said that a key rule of object-oriented programming is, “Ask, don't touch. ” How do we let user's “ask” to access instance variables? By creating methods for getting (“getters”) and setting (“setters”) instance variables.

Class with getters and setters class slide: def __init__(self, picture. File, sound. File): self. Class with getters and setters class slide: def __init__(self, picture. File, sound. File): self. set. Picture(make. Picture(picture. File)) self. set. Sound(make. Sound(sound. File)) def get. Picture(self): return self. picture def get. Sound(self): return self. sound def set. Picture(self, new. Picture): self. picture = new. Picture def set. Sound(self, new. Sound): self. sound = new. Sound def show(self): show(self. get. Picture()) blocking. Play(self. get. Sound())

Challenge Write a version of this function where you also change the sounds and Challenge Write a version of this function where you also change the sounds and pictures in the objects (using setters and getters), then replay the slide show. def playslideshow(): slide 1 = slide(get. Media. Path("barbara. jpg"), get. Media. Path("bassoon-c 4. wav")) slide 2 = slide(get. Media. Path("beach. jpg"), get. Media. Path("bassoon-e 4. wav")) slide 3 = slide(get. Media. Path("santa. jpg"), get. Media. Path("bassoon-g 4. wav")) slide 4 = slide(get. Media. Path("jungle 2. jpg"), get. Media. Path("bassoon-c 4. wav")) map(show. Slide, [slide 1, slide 2, slide 3, slide 4])

The value of objects Is this program easier to write? It certainly has less The value of objects Is this program easier to write? It certainly has less replication of code. It does combine the data and behavior of slides in one place. If we want to change how slides work, we change them in the definition of slides. We call that encapsulation: Combining data and behavior related to that data. Being able to use other objects with our objects is powerful. Being able to make lists of objects, to be able to use objects (like picture and sound) in our objects. We call that aggregation: Combining objects, so that there are objects in other objects.

We've been doing this already, of course. You've been using objects already, everywhere. Pictures, We've been doing this already, of course. You've been using objects already, everywhere. Pictures, sounds, samples, colors—these are all objects. We've been doing aggregation. We've worked with or talked about lists of pictures, sounds, pixels, and samples The functions that we've been providing merely cover up the underlying objects.

>> pic. show()" src="http://present5.com/presentation/3230cfa1dc40f11df771b3844536bde4/image-68.jpg" alt="Using picture as an object >>> pic=make. Picture(get. Media. Path("barbara. jpg")) >>> pic. show()" /> Using picture as an object >>> pic=make. Picture(get. Media. Path("barbara. jpg")) >>> pic. show()

Slides and pictures both show() Did you notice that we can say slide 1. Slides and pictures both show() Did you notice that we can say slide 1. show() and pic. show()? Show() generally means, in both contexts, “show the object. ” But what's really happening is different in each context! Slides show pictures and play sounds. Pictures just show themselves.

Another powerful aspect of objects: Polymorphism When the same method name can be applied Another powerful aspect of objects: Polymorphism When the same method name can be applied to more than one object, we call that method polymorphic From the Greek “many shaped” A polymorphic method is very powerful for the programmer. You don't need to know exactly what method is being executed. You don't even need to know exactly what object it is that you're 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 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 simply executing the method. def show(picture): if not picture. __class__ == Picture: print "show(picture): Input is not a picture" raise Value. Error picture. show()

>>" src="http://present5.com/presentation/3230cfa1dc40f11df771b3844536bde4/image-72.jpg" alt="Pictures and Colors have polymorphic methods, too >>> pic=make. Picture(get. Media. Path("barbara. jpg")) >>>" /> Pictures and Colors have polymorphic methods, too >>> pic=make. Picture(get. Media. Path("barbara. jpg")) >>> pic. show() >>> pixel = get. Pixel(pic, 100, 200) >>> print pixel. get. Red() 73 >>> color = pixel. get. Color() >>> print color. get. Red() 73

We can get/set components at either level get. Red, get. Blue, get. Green, set. We can get/set components at either level get. Red, get. Blue, get. Green, set. Red, set. Blue, set. Green Are all defined for both colors and pixels Why didn't we define the functions to work with either? It's somewhat confusing to have a globally-available function take two kinds of things as input: Colors or pixels. But it's completely reasonable to have a method of the same name in more than one object.

More methods than functions In general, there are many more methods defined in JES More methods than functions In general, there are many more methods defined in JES than there are functions. Most specifically, there a whole bunch of methods for drawing onto a picture that aren't defined as functions. We simply ran out of time/energy to convert them all into functions. And we rationalized that it was easier to deal with the complexity at the level of methods than functions.

Overview of graphics methods pic. add. Rect(color, x, y, width, height) pic. add. Rect. Overview of graphics methods pic. add. Rect(color, x, y, width, height) pic. add. Rect. Filled(color, x, y, width, height) pic. add. Oval. Filled(color, x, y, width, height)

Arcs pic. add. Arc(color, x, y, width, height, startangle, arcangle) pic. add. Arc. Filled(color, Arcs pic. add. Arc(color, x, y, width, height, startangle, arcangle) pic. add. Arc. Filled(color, x, y, width, height, startangle, arc angle) Make an arc for arcangle degrees, where startangle is the starting point. 0 = 3 o'clock. Positive arc is counter-clockwise, negative is clockwise Center of the circle is middle of the rectangle (x, y) with given height and width

Text can have style, but only limited. Java limits it for cross-platform compatibility. pic. Text can have style, but only limited. Java limits it for cross-platform compatibility. pic. add. Text(color, x, y, string) pic. add. Text. With. Style(color, x, y, string, style) Style is made by make. Style(font, emph, size) Font is sans. Serif, serf, or mono Emph is italic, bold, or plain. You can get italic, bold by italic+bold Size is a point size

Rectangles: Coloring lines and fills >>> pic=make. Picture (get. Media. Path( Rectangles: Coloring lines and fills >>> pic=make. Picture (get. Media. Path("640 x 480. jpg")) >>> pic. add. Rect. Filled (orange, 10, 100) >>> pic. add. Rect (blue, 200, 50) >>> pic. show() >>> pic. write. To("newrects. jpg") write. To() is polymorphic for both sounds and pictures.

>> pic. add. Oval" src="http://present5.com/presentation/3230cfa1dc40f11df771b3844536bde4/image-79.jpg" alt="Ovals >>> pic=make. Picture (get. Media. Path("640 x 480. jpg")) >>> pic. add. Oval" /> Ovals >>> pic=make. Picture (get. Media. Path("640 x 480. jpg")) >>> pic. add. Oval (green, 200, 50) >>> pic. add. Oval. Filled (magenta, 10, 100) >>> pic. show() >>> pic. write. To("ovals. jpg")

>>" src="http://present5.com/presentation/3230cfa1dc40f11df771b3844536bde4/image-80.jpg" alt="Arcs and colored lines >>> pic=make. Picture (get. Media. Path("640 x 480. jpg")) >>>" /> Arcs and colored lines >>> pic=make. Picture (get. Media. Path("640 x 480. jpg")) >>> pic. add. Arc(red, 10, 100, 5, 4 5) >>> pic. show() >>> pic. add. Arc. Filled (green, 200, 100, 1, 90) >>> pic. repaint() >>> pic. add. Line(blue, 400, 600, 4 00) >>> pic. repaint() >>> pic. write. To("arcs-lines. jpg")

>> pic. add." src="http://present5.com/presentation/3230cfa1dc40f11df771b3844536bde4/image-81.jpg" alt="Text examples >>> pic=make. Picture (get. Media. Path("640 x 480. jpg")) >>> pic. add." /> Text examples >>> pic=make. Picture (get. Media. Path("640 x 480. jpg")) >>> pic. add. Text(red, 100, "This is a red string!") >>> pic. add. Text. With. Style (green, 10, 200, "This is a bold, italic, green, large string", make. Style(sans. Serif, bold+italic, 18)) >>> pic. add. Text. With. Style (blue, 10, 300, "This is a blue, larger, italic-only, serif string", make. Style(serif, italic, 24)) >>> pic. write. To("text. jpg")

Sunset using methods Any of our older functions will work just fine with methods. Sunset using methods Any of our older functions will work just fine with methods. def make. Sunset(picture): for p in get. Pixels(picture): p. set. Blue(p. get. Blue()*0. 7) p. set. Green(p. get. Green()*0. 7)

Backwards using methods def backwards(filename): source = make. Sound(filename) target = make. Sound(filename) To Backwards using methods def backwards(filename): source = make. Sound(filename) target = make. Sound(filename) To get the sample object, snd. get. Sample. Object. At(index) source. Index = source. get. Length() for target. Index in range(1, target. Length()+1): # The method is get. Sample. Value, not get. Sample. Value. At source. Value =source. get. Sample. Value(source. Index) # The method is set. Sample. Value, not set. Sample. Value. At target. set. Sample. Value(target. Index, source. Value) source. Index = source. Index - 1 return target

Subclass Picture and Sound If we want to make our own methods on Picture Subclass Picture and Sound If we want to make our own methods on Picture and Sound, we have to subclass them. The new subclass will know everything from the Parent class. But we can teach it new methods.

Making sunset a method class My. Picture(Picture): def make. Sunset(self): for p in get. Making sunset a method class My. Picture(Picture): def make. Sunset(self): for p in get. Pixels(self): p. set. Blue(int(p. get. Blue()*0. 7)) p. set. Green(int (p. get. Green()*0. 7)) >>> pict = My. Picture(get. Media. Path("beach. jpg")) >>> pict. explore() >>> pict. make. Sunset() >>> pict. explore()

Making reverse a method class My. Sound(Sound): def reverse(self): target = Sound(self. get. Length()) Making reverse a method class My. Sound(Sound): def reverse(self): target = Sound(self. get. Length()) source. Index = self. get. Length() - 1 for target. Index in range(0, target. Length()): source. Value = self. get. Sample. Value. At(source. Index) target. set. Sample. Value. At(target. Index, source. Value) source. Index = source. Index - 1 return target >>> sound = My. Sound(get. Media. Path("always. wav")) >>> sound. explore() >>> target = sound. reverse() >>> target. explore()

Why objects? An important role for objects is to reduce the number of names Why objects? An important role for objects is to reduce the number of names that you have to remember. write. Sound. To() and write. Picture. To() vs. sound. write. To() and picture. write. To() They also make it easier to change data and behavior together. Think about changing the name of an instance variable. What functions do you need to change? Odds are good that they're the ones right next to where you're changing the variable. Most significant power is in aggregation: Combining objects

Python objects vs. other objects One of the key ideas for objects was “not Python objects vs. other objects One of the key ideas for objects was “not messing with the innards. ” Not true in Python. We can always get at instance variables of objects. It is true in other object-oriented languages. In Java or Smalltalk, instance variables are only accessible through methods (get. Pixel) or through special declarations (“This variable is public!”)

Inheritance We can declare one class to be inherited by another class. It provides Inheritance We can declare one class to be inherited by another class. It provides instant polymorphism. The child class immediately gets all the data and behavior of the parent class. The child can then add more than the parent class had. This is called making the child a specialization of the parent. A 3 -D rectangle might know/do all that a rectangle does, plus some more: class rectangle 3 D(rectangle):

Inheritance is a tradeoff Inheritance is talked about a lot in the object-oriented world. Inheritance is a tradeoff Inheritance is talked about a lot in the object-oriented world. It does reduce even further duplication of code. If you have two classes that will have many the same methods, then set up inheritance. But in actual practice, inheritance doesn't get used all that much, and can be confusing.

When should you use objects? Define your own objects when you have: Data in When should you use objects? Define your own objects when you have: Data in groups, like both pictures and sounds. Behavior that you want to define over that group. Use existing objects: Always—they're very powerful! Unless you're not comfortable with dot notation and the idea of methods. Then functions work just fine.