Turinys

Moduliai

Modulio įkėlimas ir kt.

Įkeliame modulį:

import moduliai_funkcijos

Įkeliame kėlimo kubu funkciją:

from moduliai_funkcijos import kubas

Įkeliame visas funkcijas (importuos visas, išskyrus tas, kurių pavadinimas prasideda „_“):

from moduliai_funkcijos import *

Panaudojame funkciją iš modulio - spausdiname 10 faktorialų:

for x in range (1, 11):
	print x, ":", moduliai_funkcijos.factorial (x)

Modulio pavadinimas:

print moduliai_funkcijos.__name__

Pridedame vieną kelią prie kelių, kuriuose ieškoma modulių:

import sys
sys.path.append ("/var/tmp/")
print sys.path

dir()

Sužinome, kas yra modulyje:

print dir(moduliai_funkcijos) # ['__builtins__', '__doc__', '__file__', '__name__', 'factorial', 'kubas']

Kas yra iš šitos bylos:

print dir() # ['__builtins__', '__doc__', '__file__', '__name__', 'factorial', 'kubas', 'moduliai_funkcijos', 'sys', 'x']

Kokie yra builtins'ai:

import __builtin__
print dir(__builtin__) # ...daug

"moduliai_funkcijos.py"

# Nelabai kam reikalingos funkcijos
 
print "Importuota moduliu byla"
 
# Modulyje esanchios funkcijos ir kintamieji registruojami tik jame,
# taigi nesimaishys su importuojanchios programos kintamaisiais.
 
def kubas (x): return x*x*x
 
def factorial (n):
	"""Apskaichiuoja n faktoriala."""
 
	if (n == 1):
		return 1
	else:
		return n * factorial (n-1)

Package'ai

Struktūros pavyzdys

	Sound					Top-level package
		__init__.py			Initialize the sound package
		Formats/			Subpackage for file format conversions
			__init__.py
			wavread.py
			wavwrite.py
			aiffread.py
			aiffwrite.py
			auread.py
			auwrite.py
			...
		Effects/			Subpackage for sound effects
			__init__.py
			echo.py
			surround.py
			reverse.py
			...
		Filters/			Subpackage for filters
			__init__.py
			equalizer.py
			vocoder.py
			karaoke.py
			...

Teorija

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as „string“, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.

Users of the package can import individual modules from the package, for example:

import Sound.Effects.echo

This loads the submodule Sound.Effects.echo. It must be referenced with its full name.

Sound.Effects.echo.echofilter(input, output, delay=0.7, atten=4)

An alternative way of importing the submodule is:

from Sound.Effects import echo

This also loads the submodule echo, and makes it available without its package prefix, so it can be used as follows:

echo.echofilter(input, output, delay=0.7, atten=4)

Yet another variation is to import the desired function or variable directly:

from Sound.Effects.echo import echofilter

Again, this loads the submodule echo, but this makes its function echofilter() directly available:

echofilter(input, output, delay=0.7, atten=4)

<…>

The import statement uses the following convention: if a package's __init__.py code defines a list named __all__, it is taken to be the list of module names that should be imported when from package import * is encountered. It is up to the package author to keep this list up-to-date when a new version of the package is released. Package authors may also decide not to support it, if they don't see a use for importing * from their package. For example, the file Sounds/Effects/__init__.py could contain the following code:

__all__ = ["echo", "surround", "reverse"]

This would mean that from Sound.Effects import * would import the three named submodules of the Sound package.

<…>

Starting with Python 2.5, in addition to the implicit relative imports described above, you can write explicit relative imports with the from module import name form of import statement. These explicit relative imports use leading dots to indicate the current and parent packages involved in the relative import. From the surround module for example, you might use:

from . import echo
from .. import Formats
from ..Filters import equalizer

<…>

Packages support one more special attribute, __path__. This is initialized to be a list containing the name of the directory holding the package's __init__.py before the code in that file is executed. This variable can be modified; doing so affects future searches for modules and subpackages contained in the package.