1 Computer Science of Graphics and Games MONT 105S, Spring 2009 Session 18 What are programs for?...

Preview:

Citation preview

1

Computer Science of Graphics and Games

MONT 105S, Spring 2009Session 18

What are programs for?Classes and Objects

2

What are Programs For?

Everything computers do is a program:Email, Web surfing, Facebook applications, Word,Tetris, Games, etc.

Programs are used in most electronic devices:Cars, TV's, Microwave ovens, cell phones

3

Why learn to program?

Programming is a useful skill in many fields:Economics, All Sciences, Business, etc.

Learning programming helps you to understand how computers function and what their limitations are.

Computer Programming is about Problem solving.•Learn to break problem into component parts•Learn to think logically•Learn to describe solutions to problems in a clear, step-by-step process.

4

Recall Classes and ObjectsA class describes a group of objects that have the same methods and set of properties.

Objects have properties: Things that describe the objectsObjects have methods: Things an object can do.

Example: A car classProperties: color, make, model, yearMethods: accelerate, brake, steer

My car is an object that is a member of the car class.color: blue, make: Honda, model: Civic, year: 2003

My husband's car is another object that is a member of the car class. color: black, make: Toyota, model: Prius, year: 2007

5

The Turtle Class

A turtle in python is an object from the Turtle class.

Properties: x position, y position, direction, pen position, etc.Methods: forward(distance), backward(distance), left(angle), etc.

When we write:yertle = Turtle( )

Python creates an object that is a member of the Turtle class.yertle is a reference to that object that we can use to access its methods using the dot notation:

yertle.forward(150)

6

Writing a Class definition

class Critter: color = "red" #color is a property mood = "happy" #mood is another property def talk(self): #talk is a method print "I am a critter!" def sing(self): #sing is another method print "Tra la la"

#main program starts herecrit = Critter( )print crit.colorcrit.talk( )crit.sing( )

7

Using self in a class method

class Critter: color = "red" mood = "happy" def talk(self): print "I am a " + self.mood + " critter!"

crit = Critter( )crit.talk( )

We can use self to refer to a given object in a class method.Example:

8

The docstring

The docstring is used to describe the objects in a class.

Example:

class Critter: """A virtual pet"""

...

crit = Critter( ):print crit.__doc__

9

The constructor functionWe can use a constructor function to initialize properties.

Example:class Critter: """A virtual pet""" def __init__(self, clr, md): self.color = clr self.mood = md def talk(self): print "I am a " + self.mood + " critter!"

crit = Critter("green", "sad")print crit.colorcrit.talk( )

Recommended