開発環境
- OS X Lion - Apple(OS)
- BBEdit - Bare Bones Software, Inc., Emacs(Text Editor)
- プログラミング言語: Python
『初めてのPython 第3版』(Mark Lutz 著、夏目 大 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-393-7)のV部(モジュール)の20章(パッケージインポート)の練習問題を解いてみる。
その他参考書籍
1, 2.
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-
import sample_dir.sample
def f():
print("Hello, Python!")
a = 20
if __name__ == '__main__':
f()
print(a)
sample_dir.sample.f()
print(sample_dir.sample.a)
path = sample_dir.sample # パス名を省略
path.f()
print(path.a)
sample_dir/sample.py
#!/usr/bin/env python3.3
#-*- coding: utf-8
a = "dir"
def f():
print("Hello, Module!")
入出力結果(Terminal)
$ ls sample_dir/* sample_dir/sample.py $ ./sample.py Hello, Python! 20 Hello, Module! dir Hello, Module! dir $
3.
python3.xではインポートするディレクトリに__init__.pyファイルを置く必要はない。
4.
名前の衝突が起こる場合には、パッケージインポートでfromではなく、importを使わなくてはならない。
0 コメント:
コメントを投稿