static keyword

Jack Diederich jack at performancedrivers.com
Thu Apr 29 15:36:21 EDT 2004


On Thu, Apr 29, 2004 at 12:09:03PM -0700, Nick Jacobson wrote:
> > 
> > Why do you call using OO ("wrapping it in a class", as you say)
> > a "hack"?  Generally speaking, using objects to contain state
> > information such as this is exactly what most people would call
> > the cleanest, best approach.
> > 
> > class HasState:
> >      def __init__(self):
> >          self.firstCall = True
> >          self.i = [10, 11]
> > 
> >      def foo(self):
> >          if self.firstCall:
> >              print "First pass"
> >              self.firstCall = False
> >          self.i[0] += 1
> >          print self.i[0]
> > 
> > obj = HasState()
> > obj.foo()
> > obj.foo()
> > 
> > Now, without arguing that it has 11 lines instead of 8 to do the
> > same thing (because then I'd just point out that this was a contrived
> > example anyway, and that it is more easily extended, and more obvious
> > what was going on, etc. :-) ), can you describe why you call this is
> > a "hack"?
> > 
> > -Peter
> 
> I don't know if "hack" is the right word.  What I meant is it seems
> like overkill to have to make (and name) a class, plus add a second
> function, every time you want a function to have a static variable.

Keeping state in functions is usually a "hack."  Class instances have
state, functions just do stuff.  That said you can get by just fine 
using default arguments for small amounts of state in functions.

def foo(i=[]):
  if (not i): # only true once
    print "First!"
    i.extend([10, 11])
  i[0] += 1
  print i[0]

But you really really don't want state in plain functions (as opposed
to member functions of objects).  I would consider any function that
does something different when called twice with the same arguments broken.
Unless the name of the function starts with 'random' *wink*.

-jackdied





More information about the Python-list mailing list