Main Content

Static variables in functions - and better ways using objects

Archive - Originally posted on "The Horse's Mouth" - 2011-10-10 23:28:18 - Graham Ellis

Usually, I don't want leftovers from a previous call to a function to hang around when I call the same function again later in my program. After all, the cosine of 45 degrees is not dependent on what the previous cosine request I made was! However, there are some occasions where I may want to have the information held, and the clue is often in the fact that I want to access the "next" result.

Languages such as PHP let you define static varaibles within a function - set up on the first call and then retaining their value. I discuss this [here] and warn about the dangers of it [here].

In Python, you can use an attribute of a function to store information between calls; you'll need to initialise it (either outside the function or in a slighly different initial call) and then you can access it each time through. for example:

  def persdemo(source = None):
    if source:
      persdemo.pieces = source.split()
    if len(persdemo.pieces) < 1:
      return None
    ending = persdemo.pieces.pop()
    return ending


There's a source code example [here] which shows an example of how to call that routine, and sample output.

But what if you want to store the data for more than one string at a time? You should be using an object! Here's a sample class - again in Python - for that:

  class persdemo(object):
    def __init__(self,string):
      self.pieces = string.split()
    def getword(self):
      if len(self.pieces) < 1:
        return None
      ending = self.pieces.pop()
      return ending


The full source code example for that, showing how to use the objects and a sample set of output may be found [here].

In Java, the StringTokenizer class (in java.util) is already written to provide functionallity like my second example above - there's an example of it in use [here] in our resource library.