2014年4月7日月曜日

開発環境

Learning Python (Mark Lutz (著)、Oreilly & Associates Inc)のPART V.(Modules and Packages)、CHAPTER 25(Advanced Module Topics)、Test Your Knowledge: Quizを解いてみる。

その他参考書籍

Test Your Knowledge: Quiz

  1. from module import * ではインポートされない。(ただし、import statement や from statementで指定することによってアクセスできる。)
  2. それがtop-levelの実行されているファイルであるということ。
  3. importlibモジュールのimport_module関数(あるいはbuilt-inの__import__関数)を使えばいい。
  4. sys.pathの変更の影響は、そのセッション、あるいはプログラムの実行の終了まで。一方、環境変数PYTHONPATHの変更の影響は、OSに依存し、プログラム、セッションが終了した後も続く。
  5. __future__によって、より阿多臘次バージョンの機能をインポートすることは出来ても、過去の機能をインポートすることは出来ない

コード(BBEdit)

sample.py

#!/usr/bin/env python3
#-*- coding: utf-8 -*-

from test1 import *
from test2 import c, _c, d, _d
module_name = 'test3'
import importlib
test3 = importlib.import_module(module_name)

print(__name__)
print(a)
try:
    print(_a)
except Exception as err:
    print(type(err), err, err.args)

print(b)
try:
    print(_b)
except Exception as err:
    print(type(err), err, err.args)

print(c, _c, d, _d)

print(test3.e, test3._e, test3.f, test3._f)

test1.py

#!/usr/bin/env python3
#-*- coding: utf-8 -*-

print(__name__)

a = 1
_a = 2
b = 3
_b = 4

test2.py

#!/usr/bin/env python3
#-*- coding: utf-8 -*-

print(__name__)

c = 5
_c = 6
d = 7
_d = 8

test3.py

#!/usr/bin/env python3
#-*- coding: utf-8 -*-

print(__name__)

e = 9
_e = 10
f = 11
_f = 12

入出力結果(Terminal)

$ ./sample.py
test1
test2
test3
__main__
1
<class 'NameError'> name '_a' is not defined ("name '_a' is not defined",)
3
<class 'NameError'> name '_b' is not defined ("name '_b' is not defined",)
5 6 7 8
9 10 11 12
$

0 コメント:

コメントを投稿