static variables in Python?

Daniel da Silva ddasilva at umd.edu
Wed Jul 30 06:30:37 CEST 2008


This is the solution I suggest. It is fairly trivial, and works by
introducing the "self.static" namespace for a class's static
variables, in contrast to "self" for the class's instance variables.

 -----------------------------------

class Static(object):  pass
personStatic = Static()

class Person:
    static = personStatic

    def __init__(self, name, age):
        self.name   = name
        self.age    = age

    def setVersion(self, version):
        self.static.version = version

    def getVersion(self):
        return self.static.version
 -----------------------------------

Daniel

On Tue, Jul 29, 2008 at 4:40 PM, kj <socyl at 987jk.com.invalid> wrote:
>
>
> Yet another noob question...
>
> Is there a way to mimic C's static variables in Python?  Or something
> like it?  The idea is to equip a given function with a set of
> constants that belong only to it, so as not to clutter the global
> namespace with variables that are not needed elsewhere.
>
> For example, in Perl one can define a function foo like this
>
> *foo = do {
>  my $x = expensive_call();
>  sub {
>    return do_stuff_with( $x, @_ );
>  }
> };
>
> In this case, foo is defined by assigning to it a closure that has
> an associated variable, $x, in its scope.
>
> Is there an equivalent in Python?
>
> Thanks!
>
> kynn
> --
> NOTE: In my address everything before the first period is backwards;
> and the last period, and everything after it, should be discarded.
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list