gobal var inside class without notice???

Michael Smith msmith at msmith.id.au
Tue Jun 14 04:53:32 EDT 2005


ajikoe at 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



More information about the Python-list mailing list