470,591 Members | 1,555 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,591 developers. It's quick & easy.

gobal var inside class without notice???

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 ???

pujo

Jul 19 '05 #1
2 1140
aj****@gmail.com 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 ???

pujo

Actually you *have* defined a global variable called 'i' - when you run
code at file scope, as you have where you wrote i = 10, all variables
are global. This means that they can be referred to anywhere in the
module, as you found.

It also means that variable accesses are slower, since accessing globals
is slower than accessing local variables. This is why many people
suggest that you define a function called main() and have the main
script simply call that.

Michael
Jul 19 '05 #2
Thanks a lot.
pujo

Jul 19 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.

By using this site, you agree to our Privacy Policy and Terms of Use.