Class variables static by default?

Cameron Simpson cs at zip.com.au
Sat Dec 19 19:44:08 EST 2009


On 19Dec2009 16:10, KarlRixon <karlrixon at gmail.com> wrote:
| Given the following script, I'd expect p1.items to just contain
| ["foo"] and p2.items to contain ["bar"] but they both contain ["foo",
| "bar"].
| 
| Why is this? Are object variables not specific to their instance?

You haven't instatiated "items" in the object instance, so python finds
it further out in the class. One class, one variable; it looks "static".

Compare this (yours):

  class Parser:
    items = []
    def add_item(self, item):
      self.items.append(item)

with this:

  class Parser:
    def __init__(self):
      self.items = []
    def add_item(self, item):
      self.items.append(item)

The first makes an "items" in the class namespace.

The second makes an "items" in each object as it is initialised.

Run the rest of your code as is and compare.

When you say "self.items" python looks first in the object and then in
the class. Your code didn't put it in the object namespace, so it found
the one in the class.

Cheers,
-- 
Cameron Simpson <cs at zip.com.au> DoD#743
http://www.cskk.ezoshosting.com/cs/

I have always been a welly man myself. They are superb in wet grass, let
alone lagoons of pig shit.      - Julian Macassey



More information about the Python-list mailing list