Intro to
Programming
with Python

Fall 2012
course
navigation

Oct 23

objects (i.e. "classes" in python)

I think the text does a pretty good job with this, so I'm just going to follow the discussion from chapter 10.

1. motivation

First, consider a program to simulate the motion of a projectile.
Discuss briefly the physics equations that are being used here.
Note that we could add a GUI and plot the trajectory with all the intermediate x and y values ... but that's not where we're headed this time.
Second, some functions can clean this up and make the main() routine clearer.
Third, consider the "object oriented programming" that we did before with the graphics module:
circle = Circle(Point(20,30)) circle.draw(window)
Can we do something like that for the cannonball?
The idea is to encapsulate the data and methods for the motion of the cannonball into a single "object". If we could do that, then we could write something like this:
def main(): angle, vel, h0, time = getInputs() cball = Projectile(angle, vel, h0) while cball.getY() >= 0: cball.update(time) print "\nDistance traveled: %0.1f meters." % (cball.getX()) main()
The advantage here is that the "cball" object contains the data; we don't need to pass it around again and again.

2. class syntax

Here's an example of using a "Multi-Sided Die" class.
$ cd /var/www/cs/htdocs/courses/fall2012/python/textbook/ppitcs_code/chapter10 $ python >>> from msdie import MSDie >>> d6 = MSDie(6) >>> d6.getValue() 1 >>> d6.roll() >>> d6.getValue() 4
And here's the msdie.py file that defines it:
Discuss

3. back to projectile

more examples

Depending on time, look at more examples are in * this directory :
The student data example, which creates a Student object to store each line of data.
(Note that both the class definition and the main method were in the same file in that example.)
The graphical dice roller example :

Mentioned "special method" names :
http://docs.python.org/reference/datamodel.html#specialnames
http://cs.marlboro.edu/ courses/ fall2012/python/ notes/ Oct_23
last modified Wednesday October 24 2012 10:32 pm EDT