I l@ve RuBoard |
PackagesPackages are a way of organizing Python modules and a way to prevent one programmer from stomping on the module of another. You assign a module to a package with the form Package_Name.Module_Name. Thus, the module name mystuff.sys indicates a module named sys in a package named mystuff. Packages are essentially directories that contain a special __init__.py file to indicate to Python that the directory it's dealing with is a package. This file is used when the package is first loaded. Let's create our own package and call it package1/__init__.py. First we create a directory called package1. Then we create a file named __init __.py with one Python statement that prints "Hello from package1", and save it to the package1 directory. Next we create a module called module1 in package1 and put in it a Python statement that prints "hello from module1 in package1". In module1, we define one do-nothing function and one do-nothing class named class1 that contains a do-nothing method named method1. Here's package1/__init__.py.
Here's package1/module1.py:
Make sure that the package1 directory is in the module search path. Then move out of package1 and fire up the Jython interpreter.
Here we see that the code in __init__.py and module1 is executed when we load class1. Now exit and restart the Jython interpreter and try this:
Notice that, when we import the package, its __init__.py module is executed. Look at the package's namespace. (Remember that the vars command is like the dir command except that it lists the namespace's names and values.) Within __init__.py you can define a list called __all__, which is used with package import* to tell Python to import all modules in this package. Actually, Python imports all modules listed in the package's __all__ list, so if you want to import a module with the * command, you have to put it in __all__. Packages can have subpackages. These are subdirectories under the package with __init__.py modules. Since __init__.py is part of the package, the package can contain anything that you find in a regular module, such as classes and functions. |
I l@ve RuBoard |
No comments:
Post a Comment