■■ モジュール ■■
モジュール(module)は Pythonの定義や文が入ったファイルです。
Pythonでは定義をファイルに書いておき、スクリプトの中やインタプリタの対話インスタンス上で使う方法があります。このファイルを モジュールと呼びます。モジュールにある定義は、他のモジュールや mainモジュール(実行のトップレベルや電卓モードでアクセスできる変数の集まりを指します)にimport(取り込み)することができます。
Pythonには多くのモジュールが用意さいれています。
モジュールはc オプションで確認することができます。
モジュールが存在する時は、以下のように何もメッセージが出ません。
> python -c "import sys"
>
以下のようにすると、モジュールの一覧が表示されます。
> python -c "help('modules')"
Please wait a moment while I gather a list of all available modules...
BaseHTTPServer antigravity imageop shelve
Bastion anydbm imaplib shlex
CGIHTTPServer argparse imghdr shutil
Canvas array imp signal
ConfigParser ast importlib site
Cookie asynchat imputil smtpd
Dialog asyncore inspect smtplib
DocXMLRPCServer atexit io sndhdr
FileDialog audiodev itertools socket
FixTk audioop json sqlite3
HTMLParser base64 keyword sre
MimeWriter bdb lib2to3 sre_compile
Queue binascii linecache sre_constants
ScrolledText binhex locale sre_parse
SimpleDialog bisect logging ssl
SimpleHTTPServer bsddb macpath stat
SimpleXMLRPCServer bz2 macurl2path statvfs
SocketServer cPickle mailbox string
StringIO cProfile mailcap stringold
Tix cStringIO markupbase stringprep
Tkconstants calendar marshal strop
Tkdnd cgi math struct
Tkinter cgitb md5 subprocess
UserDict chunk mhlib sunau
UserList cmath mimetools sunaudio
UserString cmd mimetypes symbol
_LWPCookieJar code mimify symtable
_MozillaCookieJar codecs mmap sys
__builtin__ codeop modulefinder sysconfig
__future__ collections msilib tabnanny
_abcoll colorsys msvcrt tarfile
_ast commands multifile telnetlib
_bisect compileall multiprocessing tempfile
_bsddb compiler mutex test
_codecs contextlib netrc textwrap
_codecs_cn cookielib new this
_codecs_hk copy nntplib thread
_codecs_iso2022 copy_reg nt threading
_codecs_jp csv ntpath time
_codecs_kr ctypes nturl2path timeit
_codecs_tw curses numbers tkColorChooser
_collections datetime opcode tkCommonDialog
_csv dbhash operator tkFileDialog
_ctypes decimal optparse tkFont
_ctypes_test difflib os tkMessageBox
_elementtree dircache os2emxpath tkSimpleDialog
_functools dis parser toaiff
_hashlib distutils pdb token
_heapq doctest pickle tokenize
_hotshot dumbdbm pickletools trace
_io dummy_thread pipes traceback
_json dummy_threading pkgutil ttk
_locale email platform tty
_lsprof encodings plistlib turtle
_md5 errno popen2 types
_msi exceptions poplib unicodedata
_multibytecodec filecmp posixfile unittest
_multiprocessing fileinput posixpath urllib
_osx_support fnmatch pprint urllib2
_pyio formatter profile urlparse
_random fpformat pstats user
_sha fractions pty uu
_sha256 ftplib py_compile uuid
_sha512 functools pyclbr warnings
_socket future_builtins pydoc wave
_sqlite3 gc pydoc_data weakref
_sre genericpath pyexpat webbrowser
_ssl getopt quopri whichdb
_strptime getpass random winsound
_struct gettext re wsgiref
_subprocess glob repr wx
_symtable gzip rexec wxPython
_testcapi hashlib rfc822 wxversion
_threading_local heapq rlcompleter xdrlib
_tkinter hmac robotparser xml
_warnings hotshot runpy xmllib
_weakref htmlentitydefs sched xmlrpclib
_weakrefset htmllib select xxsubtype
_winreg httplib sets zipfile
abc idlelib sgmllib zipimport
aifc ihooks sha zlib
|
モジュールは、各自で制作することができます。ファイル名はモジュール名に接尾語「.py」を付けます。モジュールの中では、(文字列の) モジュール名をグローバル変数 __name__ で取得できます。
例えば
モジュール「fibo.py」を作成
# フィボナッチ数列モジュール
def fib(n): # nまでのフィボナッチ級数を出力
a, b = 0, 1
while b < n:
print b,
a, b = b, a+b
def fib2(n): # nまでのフィボナッチ級数を返す
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
|
#モジュール「fibo.py」をimportする
import fibo
print fibo.fib(1000)
#1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
print fibo.fib2(100)
#[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
print fibo.__name__
#'fibo'