python newbie - question about lexical scoping

Hrvoje Niksic hniksic at xemacs.org
Sun Dec 2 04:31:18 EST 2007


"Matt Barnicle" <matthew at wageslavery.org> writes:

>> i have a class dict variable that apparently holds its value across
>> instantiations of new objects..
[...]
> ok, i see...  python has a concept i'm not accustomed to

I don't doubt that Python managed to confuse you here, but in this
case there is nothing really unusual or novel in Python's treatment of
class variables.  Equivalent Java code would behave exactly the same:

class Foo {
    static Map bar = new HashMap();
    static {
        bar.put("baz", "bing");
    }
}

Foo a = new Foo();
a.bar.put("baz", "bong");

Foo b = new Foo();
System.out.println(b.bar.get("baz"));
-> "bong"

> so i'm sure what is going on is obvious to experienced python
> programmers...  i'm not really sure how to get around this though.

Simply do what you'd do in any other OO language: assign a fresh value
to each instance in its constructor:

class Foo(object):
    def __init__(self):
        self.bar = {'baz': 'bing'}

Now each instance of Foo has a separate "bar" attribute dict which can
be mutated without affecting other instances.



More information about the Python-list mailing list