Class variables static by default?
Xavier Ho
contact at xavierho.com
Sat Dec 19 19:35:08 EST 2009
Yes, if you want instance variables that are unique to each instance of a
class, do the following:
class Parser:
def __init__(self):
self.items = []
And that should work fine.
J:\_Programming Projects\Python>python test.py
<__main__.Parser object at 0x0240E7B0>
<__main__.Parser object at 0x02411930>
['foo']
['bar']
Cheers,
Xav
On Sun, Dec 20, 2009 at 10:10 AM, 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)
>
> p1 = Parser()
> p1.add_item("foo")
> p2 = Parser()
> p2.add_item("bar")
>
> print p1
> print p2
> print p1.items
> print p2.items
> ----------------------------
>
> Output:
> <__main__.Parser instance at 0x7fd812ccc098>
> <__main__.Parser instance at 0x7fd812ccc0e0>
> ['foo', 'bar']
> ['foo', 'bar']
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20091220/28a55392/attachment-0001.html>
More information about the Python-list
mailing list