Python instances

M.E.Farmer mefjr75 at hotmail.com
Thu Apr 21 00:55:01 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
As others have noted, you are using a class name and not an instance
name.
Class names are shared by all instances.Instance names are not shared.
Also this next bit can bite you.
Don't use list it is builtin name and can cause problems when you
rebind it.
Others to avoid are keywords and file, dict, tuple, object, etc...
They can be tempting to use, resist, it will save you debug time later.
hth,
M.E.Farmer




More information about the Python-list mailing list