Python instances
EuGeNe
eugene at boardkulture.com
Wed Apr 20 14:56:47 EDT 2005
henrikpierrou at hotmail.com wrote:
> Hi,
>
> How do python instances work?
> Why does the code at the end of my posting produce this output:
>
> list in a:
> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
> list in b:
> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>
> instead of
>
> list in a:
> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
> list in b:
> []
>
> ----------------------------
>
> class MyClass:
> list = []
>
> def add(self, x):
> self.list.append(x)
>
> def printer(self):
> print self.list
>
> a = MyClass()
> b = MyClass()
>
> for n in range(10):
> a.add(n)
>
> print "list in a:"
> a.printer()
> print "list in b:"
> b.printer()
>
> /H
>
because list is a class member not an instance member (not sure about
the vocabulary) if in __init__ you set self.list=[] you'll get the
result you want! By declaring list=[] in the class it is shared between
all instances!
--
EuGeNe
[----
www.boardkulture.com
www.actiphot.com
www.xsbar.com
----]
More information about the Python-list
mailing list