How to initialize a class variable once
alex23
wuwei23 at gmail.com
Mon Dec 8 23:39:34 EST 2008
On Dec 9, 2:08 pm, Roy Smith <r... at panix.com> wrote:
> I've got a class with a class variable:
>
> class Foo:
> _map = {}
>
> How do I make sure this only gets initialized the *first* time the
> module containing the class is imported? What appears to be happening
> as it stands is each time the module gets imported, Foo._map get re-
> initialized.
What you're asking for is actually the default behaviour. The Foo
class should only be created once, on the first import, and all
subsequent imports should refer to it:
foo.py:
class Foo:
_map = {}
a.py:
from foo import Foo
Foo._map['a'] = 1
b.py:
from foo import Foo
print Foo._map
c.py:
import a
import b
This outputs "{'a': 1}", as expected. The Foo._map that b.py prints is
the same Foo._map that a.py has modified.
You might need to provide some more details about your code.
More information about the Python-list
mailing list