[Tutor] Q: Do Functions Have Any Class?

D-Man dsh8290@rit.edu
Wed, 28 Mar 2001 14:17:13 -0500


On Tue, Mar 27, 2001 at 11:27:31AM -0600, Curtis Larsen wrote:
| Besides their design and concept differences, is there really any
| (performance-based) reason to use classes/methods in a script as opposed
| to using functions?  Does it depend on how large your main script is? 

Classes are a template for instances which are a combination of data
and functions.  They are really useful when you have some data and
some operations that are common for that data.  You can hide the
actual data under the functions so that if the implementation changes,
clients won't have to know and will still work.

Classes also allow you to have several different, indepents sets of
the data (instances).  Functions in a module can only have persistant
state if it is in a global variable, which prevents it from being
reentrant.  This matters when using threads, or when you want to deal
with 2 independent sets of data at the same time.

If you have a simple script, or some operation that doesn't have any
persistant state (such as math operations, for example) it is better
to use a function.  

Take Java for example.  Java forces one to use a class for everything.
As a result, the Math class is composed entirely of static methods
becuase things like sqrt and pow don't have any state.  It is a
ridiculous design brought about by the requirement of classes.

When you are using python, performance is usually a moot point.  There
may be a slight difference in calling a standalone function versus an
instance function but it is not enough to be significant.

| When would you want to use one over the other?

Use the one that fits the complexity and organization of your design.

-D