Python Bibliotheca
Python resources for teachers and students.

Using classes

Here's a sample program illustrating how to use a simple geometry class that I wrote. Notice that the program begins with an import geometry line. That's because I wrote all the classes and class methods in a separate file and put that file (named 'geometry.py') in the modules folder in my home directory. If you do that, you can import your own modules too.

Have a look at this program if you get stuck. It might give you some ideas.

import geometry, string

print "This is your geometry homework helper.\n"
firstPoint = raw_input("Enter the first point (e.g., 3,6): ")
x1, y1 = string.split(firstPoint, ",")
secondPoint = raw_input("Enter the second point: ")
x2, y2 = string.split(secondPoint, ",")
p1 = geometry.Point(float(x1), float(y1))
p2 = geometry.Point(float(x2), float(y2))
l = geometry.Line(p1, p2)
print "\nLine summary:"
print "Slope: %s" % l.slope()
print "Length: %0.2f" % l.length()
midpt = l.midpt()
print "Midpoint: %s" % midpt

[ Copyright 2005, Tim Wilson ]

Comments, questions, or suggestions? Email the webmaster