Next: Operator Overloading
Up: Writing Modules
Previous: Test Programs for Modules
  Contents
Classes and Object Oriented Programming
Creating a module with a set of functions to perform useful tasks is certainly an
effective way to approach many problems.
If you find that this approach can solve all your problems, you may be content to use it
and not explore other possible ways of getting things done.
However, Python provides a simple method
for implementing object oriented programming through the use of classes. We've already
seen situations where we've taken advantage of these ideas through the methods available
for manipulating lists, dictionaries and file objects. File objects in particular show
the power of these techniques. Once you create a file object, it doesn't matter where
it came from - when you want to, say, read a line from such an object, you simply invoke
the readline method. The ability to do what you want without having to worry
about the internal details is a hallmark of object oriented programming. The main tool
in Python for creating objects is the class statement. When you create a class,
it can contain variables (often called attributes in this context) and methods. To actually
create an object that you can use in your programs, you invoke the name of its class; in
object oriented lingo we say that the class name serves as a constructor for the object.
Methods
are defined in a similar way to functions with one small difference. When you define
a method, the first argument to the method should be called self, and it represents
the object upon which the method is acting. Even though self is in the
argument list, you don't explicitly pass an object name through this argument. Instead,
as we've seen for builtin methods, you follow the name of the object with a period and the
method name and argument list.
Next: Operator Overloading
Up: Writing Modules
Previous: Test Programs for Modules
  Contents
Phil Spector
2003-11-12