gobal var inside class without notice???

Discussion in 'Python' started by ajikoe@gmail.com, Jun 14, 2005.

  1. Guest

    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
    , Jun 14, 2005
    #1
    1. Advertising

  2. 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
    Michael Smith, Jun 14, 2005
    #2
    1. Advertising

  3. Guest

    Thanks a lot.
    pujo
    , Jun 14, 2005
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Alvin Bruney

    Threads.. Session var lost, App var ok

    Alvin Bruney, Dec 2, 2003, in forum: ASP .Net
    Replies:
    1
    Views:
    349
    rooster575
    Dec 2, 2003
  2. thomson
    Replies:
    10
    Views:
    2,475
    Eliyahu Goldin
    Jun 20, 2005
  3. thomson
    Replies:
    0
    Views:
    361
    thomson
    Jun 20, 2005
  4. soft wind

    B const * array[ ] in gobal

    soft wind, Feb 8, 2010, in forum: C++
    Replies:
    14
    Views:
    608
    James Kanze
    Feb 10, 2010
  5. Dennis Ålund
    Replies:
    2
    Views:
    135
    Dennis Ålund
    Nov 29, 2005
Loading...

Share This Page