Newbie OOP Question.(diff between function, module and class)

Skip Montanaro skip at pobox.com
Mon Jun 10 11:17:09 EDT 2002


    SA> I'm still trying to grasp this OOP concept in Python. Can someone
    SA> tell me the difference between a function, a module, and a class?
    SA> Since Python defines them all as objects, how do they differ outside
    SA> of being called from inside the script or outside the script?

You posted this midday Saturday and here it's Monday morning but you still
have no replies to this question?  I would have thought people would jump
all over the opportunity to respond to a question like this.

Here's my take on things:

 * A function is an action to perform using a set of input arguments and
   returning a set of output arguments.  For example:

   >>> print sin(47)
   0.123573122745

 * A class associates a chunk of data with a set of functions which operate
   on that data.  The first argument to each function in a class (typically
   called a "method" in Python) is a reference to the data stored in that
   instance of the class.  For example:

    import math
    class Point:
        def __init__(self, x, y):
            self.x = x
            self.y = y

        def polar(self):
            return math.sqrt(self.x**2+self.y**2), math.atan2(self.y, self.x)

 * A module is an object that partitions the namespace in a hierarchy.  For
   example, you can have a function named "sin" which is distinct from the
   sin function in the math module ("math.sin").  Modules used in a
   straightforward way only add a single extra level of hierarchy to the
   namespace.  Packages generalize this concept to multiple levels (modules
   inside modules).

-- 
Skip Montanaro (skip at pobox.com - http://www.mojam.com/)
Boycott Netflix - they spam - http://www.musi-cal.com/~skip/netflix.html






More information about the Python-list mailing list