Variable scope within a class

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Graham

    Variable scope within a class

    How do I make a variable available to code *inside* my class in such a way
    that it is available to all defs in the class? In my example below f is not
    accessible within the showVars method.

    class myClass:
    f = [1,2,3]

    def showVars ( self ):
    print f # Error here as f does not exist

    def main():
    x = myClass()
    print x.f
    x.showVars()

    if __name__ == "__main__":
    main()


    Thanks to anyone who can offer some guidance to a Python beginner!
    Graham.



  • Nuff Said

    #2
    Re: Variable scope within a class

    On Tue, 03 Feb 2004 10:11:43 +0000, Graham wrote:
    [color=blue]
    > How do I make a variable available to code *inside* my class in such a way
    > that it is available to all defs in the class? In my example below f is not
    > accessible within the showVars method.[/color]

    It depends on whether you want to have a class variable or an instance
    variable; looking at the following variation of your code should make
    clear the difference:

    class myClass:
    f = [1, 2, 3]

    def showVars(self):
    print self.f


    class myClass2:
    def __init__(self):
    self.f = ['a', 'b']

    def showVars(self):
    print self.f


    print myClass.f

    myc = myClass()
    myClass.f = [4, 5, 6]
    myc.showVars()

    myc2 = myClass2()
    myClass2.f = ['c', 'd'] # this f is created here!!!
    print myClass2.f
    myc2.showVars()


    +++ OUTPUT +++

    [1, 2, 3]
    [4, 5, 6]
    ['c', 'd']
    ['a', 'b']


    Remark: 'Normally', you want something like myClass2.

    HTH / Nuff

    Comment

    • Gerrit Holl

      #3
      Re: Variable scope within a class

      Hi Graham,
      [color=blue]
      > How do I make a variable available to code *inside* my class in such a way
      > that it is available to all defs in the class? In my example below f is not
      > accessible within the showVars method.
      >
      > class myClass:
      > f = [1,2,3]
      >
      > def showVars ( self ):
      > print f # Error here as f does not exist[/color]

      Since f is a class variable, it is also an instance variable. You can
      either reach it by referring to the class or by referring to the
      instance. The former can be done with 'self.__class__ .f', the latter by
      the simpler 'self.f'. The difference is that, if self.f changes, this is
      true for only 1 instance of the class, while all share the same
      self.__class__. f.

      Gerrit.

      --
      PrePEP: Builtin path type

      Asperger's Syndrome - a personal approach:


      Comment

      • Graham

        #4
        Re: Variable scope within a class

        Thanks Gerrit and Nuff Said. Very helpful indeed.

        Graham


        Comment

        Working...