By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,767 Members | 1,987 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,767 IT Pros & Developers. It's quick & easy.

gobal var inside class without notice???

P: n/a
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
Share this Question
Share on Google+
2 Replies


P: n/a
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

P: n/a
Thanks a lot.
pujo

Jul 19 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.