Class variables static by default?

John Posner jjposner at optimum.net
Sat Dec 19 19:29:57 EST 2009


On Sat, 19 Dec 2009 19:10:13 -0500, 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?
>
> ---------------------------
> #!/usr/bin/env python
>
> class Parser:
> 	items = []
> 	def add_item(self, item):
> 		self.items.append(item)
>

<snip>

You're using a *class attribute* instead of an *instance attribute*.
Change the class definition to:

class Parser:
     def __init__(self):
         self.items = []

     def add_item(self, item):
         self.items.append(item)

-John



More information about the Python-list mailing list