Module
Python für Programmierer WS06/07
Moduldefinition
mein_modul.py:
text = "Tach." def meine_funktion(a, b, c): return a + b * c
mein_programm.py:
import mein_modul print mein_modul.text # -> Tach. print mein_modul.meine_funktion(10, 2, 3) # -> 16 (10 + 2 * 3)
- Jede python-Datei ist ein eigenes Modul
- Mit import kann auf alle Objekte in dem Modul zugegriffen werden
from-importe
from mein_modul import text, meine_funktion print mein_modul.text # -> Tach. print mein_modul.meine_funktion(10, 2, 3) # -> 16 (10 + 2 * 3)
- Mit from ... import ... kann man einzelne Objekte importieren
- Nützlich, um den Namensraum sauber zu halten
Beispiele für Standardmodule
random:
>>> import random >>> random.randint(0, 100) # Zufallszahl 0 <= x < 100 67 >>> random.random() # Zufallszahl 0.0 <= x < 1.0 0.4108313174725905 >>> help(random) # Hilfe zum Modul
sys:
>>> import sys >>> print sys.version 2.4.4c0 (#2, Jun 15 2006, 01:13:21) [GCC 4.1.2 20060613 (prerelease) (Debian 4.1.1-4)] >>> sys.platform 'linux2'
math:
>>> import math >>> math.pi 3.1415926535897931
Modulglobaler Code
modul.py:
print "modul.py wird ausgeführt!" def funktion(): print "funktion wird ausgeführt"
programm.py:
import modul # -> "modul.py wird ausgeführt!" modul.funktion() # -> "funktion word ausgeführt"
Main-Hook
Eine Python-Datei kann sowohl als Hauptprogramm als auch als Modul fungieren.
Um zu unterscheiden, welche Rolle eine Python-Datei übernimmt, verwendet man folgenden Code:
print "Das hier wird immer ausgeführt." if __name__ == '__main__': print "Das hier wird nur ausgeführt, wenn diese Datei das Hauptprogramm ist."