S Borg schreef: > 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' > > #######interpreter######### >>>> x = MyClass() >>>> (unhelpful error mesages) > > I hope I have clearly explained my problem.
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.MyClass() 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 -- http://mail.python.org/mailman/listinfo/python-list