2012年7月27日金曜日

開発環境

『初めてのPython 第3版』(Mark Lutz 著、夏目 大 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-393-7) のV部(パッケージインポート)の20章(パッケージインポートとインポート)練習問題1を解いてみる。

1.

__init__.pyファイルの役割はパッケージインポートの際の初期化処理。

コード(TextWrangler)

sample.py

#!/usr/bin/env python
#encoding: utf-8

a = 10
b = "Python"
def f():
 print("Hello, Python!")

入出力結果(Terminal)

$ ls -R sample_folder
sample_folder

sample_folder/sample_folder:
sample.py
$ python
Python 3.2.3 (default, Apr 18 2012, 20:17:30) 
[GCC 4.2.1 Compatible Apple Clang 3.0 (tags/Apple/clang-211.12)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sample_folder.sample_folder.sample
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named sample_folder.sample_folder.sample
>>> quit()
$ vi sample_folder/__init__.py
$ vi sample_folder/sample_folder/__init__.py
$ ls -R sample_folder
sample_folder

sample_folder/sample_folder:
sample.py
$ vi sample_folder/__init__.py
$ vi sample_folder/sample_folder/__init__.py
$ python
Python 3.2.3 (default, Apr 18 2012, 20:17:30) 
[GCC 4.2.1 Compatible Apple Clang 3.0 (tags/Apple/clang-211.12)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sample_folder.sample_folder.sample
>>> sample_folder.sample_folder.sample.a
10
>>> sample_folder.sample_folder.sample.b
'Python'
>>> sample_folder.sample_folder.sample.f()
Hello, Python!
>>> from sample_folder.sample_folder.sample import *
>>> a
10
>>> b
'Python'
>>> f()
Hello, Python!
>>> quit()
$

0 コメント:

コメントを投稿