7 Objects, Classes and What They Mean to You

If you are an object-oriented programmer, you'll find Python a pleasure to use: it provides a well-integrated object model with pretty much all of the tools you expect in an object-oriented language. But nothing forces you to write classes in Python. You can write traditional procedural code just fine if you think OO stuff is for namby pamby dweebs. Nonetheless, it is helpful to know a bit about it since many of the the standard libraries are written with objects in mind. Learning to use objects is much easier than learning how to write good classes.

Typically an object is created by calling a function (or at least something that looks like a function) and assigning the return value to a variable. Thereafter you may access and modify attributes of the object (its local variables, in effect). You can perform operations on the object (or have it perform actions) by calling its 'methods'. File handles provide a good example of what we mean.

>>> fin = open('input.txt','r') # open file in read mode and return file handle
>>> lines = fin.readlines()     # call a method that returns a list of lines
>>> for line in lines: print line
>>> print fin.name              # print name of the file for the fin object
                                # 'name' is an attribute of the file object
>>> fin.close()                 # close the file

This approach is used by many Python libraries.

Questions or comments? Contact help@stsci.edu
Documented updated on 2004 Jun 1