Static Variables in Python?

Cameron Laird claird at lairds.us
Mon Aug 7 13:46:53 EDT 2006


In article <1154378719.157643.98340 at p79g2000cwp.googlegroups.com>,
Paddy <paddy3118 at netscape.net> wrote:
			.
		[substantial thread
		with many serious
		alternatives]
			.
			.
>You can do things with function attributes
>
>def foo(x):
>  foo.static += x
>  return foo.static
>foo.static = 0
			.
			.
			.
My favorite variation is this:

  def accumulator(x):
          # On first execution, the attribute is not yet known.
  	# This technique allows use of accumulator() as a 
  	# function without the "consumer" having to initialize
  	# it.
      if not "static" in dir(accumulator):
  	accumulator.static = 0
      accumulator.static += x
      return accumulator.static
  
  print accumulator(3)
  print accumulator(5)



More information about the Python-list mailing list