Static Variables in Python?

Paddy paddy3118 at netscape.net
Tue Aug 8 02:00:50 EDT 2006


Cameron Laird wrote:
> 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)

Thanks Cameron, I'll accumulate this in my toolbox.

- pad.




More information about the Python-list mailing list