CS 1 Lecture 12

Classes and objects, continued

Professor Devin Balkcom
devin@cs.dartmouth.edu
office: Sudikoff 211

http://www.cs.dartmouth.edu/~cs1

Notes

Classes

Python does not have a built-in ball type.

Class: when we create an object, here's what it will be like. A class is the definition of a custom type.


Example. I can tell you how a list works. There are ways to index the data, and operations we can perform. That description is the list class. (The list class is built in.)

The list object is the data in memory: [1, 2, 18, 2]

Object-oriented design

Larger programs need better ways of organizing.

Object-oriented design: define custom data types (classes), and methods that work on objects.


Two benefits:

Custom Ball class

We need to know:

Classes

Method definition

def update_position(self, timestep):
  self.x += timestep * self.v_x
  self.y += timestep * self.v_y     

In general: method_name(self, parm1, ...)

self is the name of the parameter that holds the reference to the object.

It is always called self, and you must include it.

Method call

ball.update_position(TIMESTEP)    

method call:
  reference_to_object.method_name(parm1, ...)

You must have a reference to an object to call a method.

Constructors

myball = Ball(10.0, 15.0, 0.0, -5.0)

A constructor function is automatically generated by Python for each class, with the same name as the class.

A constructor does three things:

__init__() method

The special __init__() method

Pair exercise: cascade