Python Class use

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

    #1

    Python Class use


    Hello,

    I am running Python on Mac OS X. The interpreter has been great for
    learning the basics, but I would now like to be able to reuse code.
    How do I write reusable code? I have done it "The Java way": write
    the class, and save it to my home directory, then call it from the
    interpreter, here is an example.

    ########my saved file######
    class MyClass:
    def f(self):
    return 'calling f from MyClass'

    #######interpre ter#########[color=blue][color=green][color=darkred]
    >>> x = MyClass()
    >>> (unhelpful error mesages)[/color][/color][/color]

    I hope I have clearly explained my problem. Because I
    don't know the solution top this, I have to rewrite my methods
    in the interpreter every single time I need to change something, and
    I am quite certain that that is not the best way to do it.

    Thank you very much.

    S

  • Roy Smith

    #2
    Re: Python Class use

    S Borg <spwpreston@gma il.com> wrote:[color=blue]
    > I am running Python on Mac OS X. The interpreter has been great for
    > learning the basics, but I would now like to be able to reuse code.[/color]

    Excellent. Code reuse is what it's all about!
    [color=blue]
    > How do I write reusable code? I have done it "The Java way": write
    > the class, and save it to my home directory, then call it from the
    > interpreter[/color]

    That's pretty much what you do in Python. Write your class into a
    file called foo.py and save it. Then, start up an interpreter and do
    "import foo". You might want to read about "modules" in the Python
    tutorial (http://docs.python.org/tut/node8.html).

    Comment

    • Fabiano Sidler

      #3
      Re: Python Class use

      Huh? You definitely must import that module. Then, is your homedir
      listed in sys.path?

      Greetings,
      F. Sidler

      Comment

      • Roel Schroeven

        #4
        Re: Python Class use

        S Borg schreef:[color=blue]
        > Hello,
        >
        > I am running Python on Mac OS X. The interpreter has been great for
        > learning the basics, but I would now like to be able to reuse code.
        > How do I write reusable code? I have done it "The Java way": write
        > the class, and save it to my home directory, then call it from the
        > interpreter, here is an example.
        >
        > ########my saved file######
        > class MyClass:
        > def f(self):
        > return 'calling f from MyClass'
        >
        > #######interpre ter#########[color=green][color=darkred]
        >>>> x = MyClass()
        >>>> (unhelpful error mesages)[/color][/color]
        >
        > I hope I have clearly explained my problem.[/color]

        I think so.

        Python does this different from Java. One difference is that Python
        allows you to put more than one class in a module (you also don't have
        to put everything in a class; code can live in a module's global
        namespace too). Then, to use code from that module, you have to import
        it with the import statement.

        Putting it all together, you could create a file MyModule.py which
        contains the code you mentioned, and then use it like this:

        import MyModule

        x = MyModule.MyClas s()
        x.f()

        Or you could directly import MyClass into the global namespace like this:

        from MyModule import MyClass

        x = MyClass()
        x.f()

        But that's not recommended since it clutters the global namespace and
        makes it more difficult to see which name comes from which module.


        --
        If I have been able to see further, it was only because I stood
        on the shoulders of giants. -- Isaac Newton

        Roel Schroeven

        Comment

        • Magnus Lycka

          #5
          Re: Python Class use

          Roel Schroeven wrote:[color=blue]
          > import MyModule
          >
          > x = MyModule.MyClas s()
          > x.f()
          >
          > Or you could directly import MyClass into the global namespace like this:
          >
          > from MyModule import MyClass
          >
          > x = MyClass()
          > x.f()
          >
          > But that's not recommended since it clutters the global namespace and
          > makes it more difficult to see which name comes from which module.[/color]

          No, no, it's completely kosher to use "from module import Class".
          It won't clutter the namespace any more than the above as long
          as you just import one class, and there's no "magically" appearing
          names in any namespace. You should avoid "from module import *" in
          your programs though, but feel free to use it in the interpreter.

          Just using "from MyModule import *" and then simply using "MyClass"
          in the code is confusing for others who read your code, since it's
          not appearent where MyClass came from. As your progam grows and you
          use more modules, it will get worse. Imagine that you have three
          modules and do:

          from module1 import *
          from module2 import *
          from module3 import *

          How on earth will someone reading that progam know where to find the
          definition of a class or function then, and what will happen if you
          happened to use the same class or function name in more than one
          module? As software grows, it gets more and more important to prevent
          such problems.

          With either "from module1 import Class1, Class2" or "import module1"
          follwed by "o = module1.Class1( )" etc, it will always be clear from
          the source code file where Class1 is used, where it's defined. The
          "from ... import ..." style means that you need to find the import
          statement to figure out where it's from, so the plain "import x"
          might be preferable, but that's a judgement call you need to make
          from case to case.

          But more importantly, I think "S" should realize that while the
          interpreter is nice as a calculator etc and for experiments, the
          normal way to use Python is to put practically all your code in
          files. It's common to write code so that it's both useful as a
          module and a stand alone program. You achieve by looking at the
          "magic" __name__ variable, which is set to "__main__" if a script
          is used as direct input to python, and to the file name (sans .py)
          if imported.

          E.g. if you have a file "whoami.py" containing just "print __name__",
          doing "python whoami.py" will print out "__main__", but doing an
          "import whoami" from the interpreter would print out "whoami".

          So, if you want some code to check how many files and/or directories
          you have in your current directory, you could make a module like this:

          filecount.py---------------

          import os

          def filecount():
          return len(os.listdir( '.'))

          if __name__=='__ma in__':
          print "There are", filecount(), "entries in the current directory"

          ---------------------------

          Then, "python filecount.py" might display

          There are 12 entries in the current directory

          while an interactive session might give:
          [color=blue][color=green][color=darkred]
          >>> import filecount
          >>> print filecount.filec ount()[/color][/color][/color]
          12[color=blue][color=green][color=darkred]
          >>>[/color][/color][/color]

          Comment

          • bruno at modulix

            #6
            Re: Python Class use

            S Borg wrote:[color=blue]
            > Hello,
            >
            > I am running Python on Mac OS X. The interpreter has been great for
            > learning the basics, but I would now like to be able to reuse code.
            > How do I write reusable code? I have done it "The Java way": write
            > the class, and save it to my home directory, then call it from the
            > interpreter, here is an example.
            >
            > ########my saved file######
            > class MyClass:
            > def f(self):
            > return 'calling f from MyClass'
            >
            > #######interpre ter#########
            >[color=green][color=darkred]
            >>>>x = MyClass()
            >>>>(unhelpfu l error mesages)[/color][/color][/color]

            This message - that is called a 'traceback' - may seem unhelpful to you,
            but as a general rule, please post it : it may be *very* helpful to
            those trying to help you (well, in this case the problem is pretty
            obvious, but most of the time it is not...)

            NB: see other answers in this thread about your actual problem - and
            please take time to read the Fine Manual, specially:



            --
            bruno desthuilliers
            python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
            p in 'onurb@xiludom. gro'.split('@')])"

            Comment

            Working...