oct 26
First discuss projects : how did they go?
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/fall2010/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
- class definition
- "module" : a file with a class definition in it
- module documentation
- variables within an "instance" of an object
- "self"
- as argument in function definition
- ... but not mentioned when method is invoked with thing.method()
- (The programming language conventions here are python specific.)
- special method: __init__ constructor
3. back to projectile
more examples
The student data example, which creates a Student object to store each line of data.
- gpa.py (code)
- students.dat (data)
(Note that both the class definition and the main method were in the same file in that example.)
The graphical dice roller example :
- roller.py
- button.py
- dieview.py
- graphics.py