[Tutor] is this a bug global i ???

Marilyn Davis marilyn at deliberate.com
Tue Jun 14 19:06:28 CEST 2005


On Tue, 14 Jun 2005, Pujo Aji wrote:

> I have code like this:
> 
> class A:
>   def __init__(self,j):
>     self.j = j
>   
>   def something(self):
>     print self.j
>     print i            # PROBLEM is here there is no var i in class A
> but it works ???
> 
> if __name__ == '__main__':
>   i = 10
>   a = A(5)
>   a.something()
> 
> I don't define global i but it will takes var i from outside of class A.
> 
> Can somebody explain this ???

The i is 'global' by placement so it can be read.

But you can't assign it in a.something().  If you do:

 class A:
   def __init__(self,j):
     self.j = j
   
   def something(self):
     print self.j
     i = 11      # makes a new local i in something
     print i       

 if __name__ == '__main__':
   i = 10
   a = A(5)
   a.something()
   print 'i = ', i   # prints the same old global i = 10

You'll find you made a new i in something and your i = 10 remains the same.

But, if you want to change the global i, in something, then it's time
for the global declaration:

   def something(self):
     global i
     print self.j
     i = 11            # changes the global i
     print i            
  
Hope this helps. I had the same confusion long ago and this list helped me.

Marilyn Davis


> 
> pujo
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 



More information about the Tutor mailing list