gobal var inside class without notice???

A

ajikoe

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
 
M

Michael Smith

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top