week 8

25
Week 8 Classes and Objects Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this work is licensed under: http://creativecommons.org/licenses/by-nc-sa/3.0

Upload: terra

Post on 08-Jan-2016

30 views

Category:

Documents


0 download

DESCRIPTION

Week 8. Classes and Objects Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this work is licensed under: http://creativecommons.org/licenses/by-nc-sa/3.0. OOP, Defining a Class. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Week 8

Week 8

Classes and ObjectsSpecial thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides.

Except where otherwise noted, this work is licensed under:http://creativecommons.org/licenses/by-nc-sa/3.0

Page 2: Week 8

2

OOP, Defining a Class

• Python was built as a procedural language– OOP exists and works fine, but feels a bit more "tacked

on"

– Java probably does classes better than Python (gasp)

• Declaring a class:

class name: statements

Page 3: Week 8

3

Fieldsname = value

– Example:class Point: x = 0 y = 0

# mainp1 = Point()p1.x = 2p1.y = -5

– can be declared directly inside class (as shown here)or in constructors (more common)

– Python does not really have encapsulation or private fields

• relies on caller to "be nice" and not mess with objects' contents

point.py

123

class Point: x = 0 y = 0

Page 4: Week 8

4

Using a Class

import class

– client programs must import the classes they use

point_main.py

12345678

from Point import *

# mainp1 = Point()p1.x = 7p1.y = -3

...

Page 5: Week 8

5

"Implicit" Parameter (self)

• Java: this, implicitpublic void translate(int dx, int dy) { x += dx; // this.x += dx; y += dy; // this.y += dy;}

• Python: self, explicit– self must be the first parameter to any object method– must access the object's fields through the self

reference

def translate(self, dx, dy): self.x += dx self.y += dy...

Page 6: Week 8

6

Methodsdef name(self, parameter, ..., parameter): statements

– additional parameters are optional

– Example:class Point: def translate(self, dx, dy): self.x += dx self.y += dy ...

– Exercise: Write distance and distance_from_origin .

Page 7: Week 8

7

Exercise Answer

point.py

123456789

10111213

from math import *

class Point: x = 0 y = 0

def distance_from_origin(self): return sqrt(self.x * self.x + self.y * self.y)

def distance(self, other): dx = self.x - other.x dy = self.y - other.y return sqrt(dx * dx + dy * dy)

Page 8: Week 8

8

Constructorsdef __init__(self, parameter, ..., parameter): statements

– a constructor is a special method with the name __init__

– Example:

class Point: def __init__(self, x, y): self.x = x self.y = y

...

Page 9: Week 8

9

toString and __str__

def __str__(self):

return string

– equivalent to Java's toString (converts object to a string)

– invoked automatically when str or print is called

def __str__(self):

return "(" + str(self.x) + ", " + str(self.y) + ")"

– Others: define a < on your class by writing __lt__ , etc.:http://docs.python.org/ref/customization.html

Page 10: Week 8

10

Complete Point Classpoint.py

123456789101112131415161718192021

from math import *

class Point: def __init__(self, x, y): self.x = x self.y = y

def distance_from_origin(self): return sqrt(self.x * self.x + self.y * self.y)

def distance(self, other): dx = self.x - other.x dy = self.y - other.y return sqrt(dx * dx + dy * dy)

def translate(self, dx, dy): self.x += dx self.y += dy

def __str__(self): return "(" + str(self.x) + ", " + str(self.y) + ")"

Page 11: Week 8

11

Inheritanceclass name(superclass): statements

– Example:class Point3D(Point): # Point3D extends Point z = 0 ...

• Python also supports multiple inheritance

class name(superclass, ..., superclass): statements

Page 12: Week 8

12

Calling Superclass Methods

• methods: class.method(parameters)

• constructors: class.__init__(parameters)

class Point3D(Point): z = 0 def __init__(self, x, y, z): Point.__init__(self, x, y) self.z = z

def translate(self, dx, dy, dz): Point.translate(self, dx, dy) self.z += dz

Page 13: Week 8

13

The pyGame Package

• A set of Python modules to help write games

• Deals with media (pictures, sound) nicely

• Interacts with user nicely (keyboard, joystick, mouse input)

Page 14: Week 8

14

Where to Start?

• The official pyGame website

• Search for tutorials

• The Application Programming Interface (API)– specifies the classes and functions in package

• Experiment!

Page 15: Week 8

15

A Skeleton

• Tutorials basically all have the same setup -- let's use it!template.py

1234567891011121314151617

from pygame import *from pygame.sprite import *from random import *

init()

screen = display.set_mode((640, 480))display.set_caption('Whack-a-mole')

while True: e = event.poll() if e.type == QUIT: quit() break

screen.fill(Color("white")) display.update()

Page 16: Week 8

16

Surface

• All images are represented as Surfaces

• display.set_mode(x, y) returns a Surface object

• fill("color") fills the object it's called on

• blit(surface, area) paints surface onto the object it's called on in the rectangle bounded by area

Page 17: Week 8

17

Rect

• Objects that store rectangular coordinates

• center holds the object's center as a tuple

• colliderect(target) returns True if the parameter overlaps with the object

• collidepoint(target) returns True if the target point overlaps with the object

Page 18: Week 8

18

Media

• Loading an image:– img = image.load("file.gif").convert()

• Getting a bounding rectangle:– img_rect = img.get_rect()

• Loading and playing a sound file:– mixer.Sound("file.wav").play()

Page 19: Week 8

19

Sprite

• Class visible game objects inherit from

Ball.py

1234567891011

from pygame import *from pygame.sprite import *

class Ball(Sprite): def __init__(self): Sprite.__init__(self) self.image = image.load("ball.png").convert() self.rect = self.image.get_rect()

def update(self): self.rect.center = mouse.get_pos()

Page 20: Week 8

20

Using Sprites

• They're just objects: initialize them– ball = Ball()

• Create a group of sprites in main– sprites = RenderPlain(sprite1, sprite2)

• Groups know how to draw and update– sprites.update()– sprites.draw(surface)

Page 21: Week 8

21

Exercise: Whack-a-mole

• Clicking on the mole– plays a sound– makes the mole move

• The number of hits is displayed at the top of the screen

• For version 2, hit the mole with a shovel

Page 22: Week 8

22

Using Resources

• You should now be more comfortable with using APIs

• Never be afraid to experiment!

• The Python community is very open to questions.

Page 23: Week 8

23

SciPy

• Math, science, engineering tools

• Official website (http://www.scipy.org/)

• Installation (http://www.scipy.org/Installing_SciPy)

• Cookbook (http://www.scipy.org/Cookbook)

• Tutorial (http://www.tau.ac.il/~kineret/amit/scipy_tutorial/)

• API (http://www.scipy.org/doc/api_docs/)

Page 24: Week 8

24

Django

• Web application framework

• Official website (http://www.djangoproject.com/)

• Free book (http://www.djangobook.com/)

• API (http://www.djangoproject.com/documentation/db-api/)

Page 25: Week 8

25

So Many Packages!

• Official listing (http://pypi.python.org/pypi?%3Aaction=browse)

• If it doesn't exist, make your own!

The sky's the limit!