Someone enlightened me

Gary Herron gherron at islandtraining.com
Sun Jul 13 11:23:28 EDT 2008


Marcus Low wrote:
> Opps here is the mail again, incase my formatting is lost, can someone 
> explain to me why this code behaves differently when "lister" and 
> "self.lister" is swap remarked.
>
>
> class abc :
>    # remark this later and unremark "self.lister"
>    lister = []
>    def __init__ (self, val):
>        #self.lister = []
>        self.lister.append(val) 
> globallist = []
>  
> def test () :
>
>    global l
>    for x in range(10) :
>        o = abc(x)              globallist.append(o)                 o 
> = ""
>          for i in globallist :
>        print i.lister        
> test()      
>
> -- 
> http://mail.python.org/mailman/listinfo/python-list

It's a Python scoping rule:

    If a variable is assigned to anywhere within a function,
    it is assumed to be local *everywhere* within that function.

See the faq for more:
  
http://www.python.org/doc/faq/programming/#what-are-the-rules-for-local-and-global-variables-in-python

Gary Herron




More information about the Python-list mailing list