Newbie asks about static variables...

Martijn Faassen faassen at pop.vet.uu.nl
Tue May 4 14:44:16 EDT 1999


stephen.allison at cenes.co.uk wrote:
[snip static variable example in C]
> If i try to do copy the above 'directly' into python no_of_calls is reset each
> time the function is called (which is fair enough), and I can only acjieve the
> required behaviour by having decaling number_of_calls as 'global', which
> doesn't seem very elegant.  It seems a funny thing not to be in a language
> which is other wise very nice.  Perhaps I'm not 'thinking in python' yet, can
> anyone shed some light?

Well, using a global variable would indeed be one way. One need not be
as worried with global variables in Python, as there's a nice module
system that puts them in their own namespaces. If you prepend your
global variable with a _ then it doesn't get imported, even if you use
'from <module> import *'.

Another option is to use a class for this kind of behavior.

class Foo:
    amount = 0 # class variable, could use instance variable too
    def __call__(self):
        """Objects of this class can be called like functions.
        """
        self.amount = self.amount + 1
        print "You called me %s times." % self.amount
foo = Foo() # instantiate a single instance as a function

# call the 'function'
foo()
foo()
foo()

Regards, and good luck,

Martijn




More information about the Python-list mailing list