[Tutor] is this a bug global i ???
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)
> 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:
self.j = j
i = 11 # makes a new local i in something
if __name__ == '__main__':
i = 10
a = A(5)
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:
i = 11 # changes the global i
Hope this helps. I had the same confusion long ago and this list helped me.
> Tutor maillist - Tutor at python.org
More information about the Tutor