開発環境
- OS X Lion - Apple(OS)
- TextWrangler(Text Editor) (BBEditの無料機能制限版、light版)
- Script言語: Python
『初めてのPython 第3版』(Mark Lutz 著、夏目 大 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-393-7) のIV部(関数)16章(スコープと引数)練習問題を解いてみる。
1, 2, 3, 4, 5, 6の実行結果はそれぞれ以下のようになる。
Spam #1 Spam #2 NI #3 Spam NI #4 NI #5 Spam 1, 5, 6, 4 #6
確認。
入出力結果(Terminal)
$ python Python 2.7.2 (default, Feb 12 2012, 23:50:38) [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. >>> X='Spam' >>> def f(): ... print X ... >>> f() Spam >>> X='Spam' >>> def f(): ... X='NI' ... >>> f() >>> print X Spam >>> X='Spam' >>> def f(): ... X='NI' ... print X ... >>> f() NI >>> print X Spam >>> X='Spam' >>> def f(): ... global X ... X='NI' ... >>> f() >>> print X NI >>> X='Spam' >>> def f(): ... X='NI' ... def nested(): ... print X ... nested() ... >>> f() NI >>> X 'Spam' >>> def f(a,b,c=3,d=4):print a,b,c,d ... >>> f(1,*(5,6)) 1 5 6 4 >>> quit() $
7.
Pythonの関数でステート情報を保持するには、
- globalを使う。
- 関数の外側の変数を使う。
- 引数のデフォルト値を使う。
という3つの方法がある。
8.
関数が呼び出し側に影響を与えるには、
- return文で値を戻す。
- globalを使って変数に変更を加える。
- 可変生オブジェクトを引数に渡して変更を加える。
という3つの方法がある。
0 コメント:
コメントを投稿