namespace question

Jean-Michel Pichavant jeanmichel at sequans.com
Fri Feb 24 06:56:01 EST 2012


xixiliguo wrote:
> c = [1, 2, 3, 4, 5]
> class TEST():
>     c = [5, 2, 3, 4, 5]
>     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
>   

Attributes can only accessed by explictly naming the owner, unlike some 
other languages which infer 'this/self'.
When an attribute is not found in the owner, python may look into the 
"outer" namespace. Read the python documentation for an accurate 
description.


Here is an illustration (python 2.5):

c='global'

class TEST():
  c = 'class'
  d = 'classonly'
  def __init__(self):
    self.c='instance'
  def test(self):
    print c
    print TEST.c
    print self.c
    print self.d # this is valid, if d is not found in the instance, 
python will look into the class

t = TEST()

t.test()

global
class
instance
classonly


Note that objects in python are properly named namespaces. locals and 
globals are not, so be careful while naming those (in few words: don't 
use globals)

c = 'global'

def foo():
  c = 'local'
  print c # same name for 2 different objects

def bar():
  print c
  global c # the global statement is quite strange, it applies to the 
whole block, even previous statements, ppl usually put it at the 
begining of the block though

foo()
bar()

'local'
'global'

Cheers,

JM



More information about the Python-list mailing list