namespace question

Chris Rebert clp2 at rebertia.com
Fri Feb 24 07:35:07 CET 2012


On Thu, Feb 23, 2012 at 9:55 PM, xixiliguo <wangbo.red at gmail.com> wrote:
> c = [1, 2, 3, 4, 5]
> class TEST():
>    c = [5, 2, 3, 4, 5]

That line creates a class (i.e. "static") variable, which is unlikely
to be what you want. Instance variables are normally created in the
body of an __init__() method.

>    def add( self ):
>        c[0] = 15
>
> a = TEST()
>
>
> a.add()
>
> print( c, a.c, TEST.c )
>
> result :
> [15, 2, 3, 4, 5] [5, 2, 3, 4, 5] [5, 2, 3, 4, 5]
>
>
> why a.add() do not update c in Class TEST? but update c in main file

Python is not Java (or similar). To refer to instance variables, you
must explicitly use `self`; i.e. use "self.c[0] = 15" in add().

I would recommend reviewing the relevant section of the Python tutorial:
http://docs.python.org/tutorial/classes.html

Cheers,
Chris



More information about the Python-list mailing list