Python 2.4 クイックリファレンス | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
目次
この文書について
バージョン 2.4
日本語訳(現在鋭意翻訳中):
Tip: Python インタプリタに 起動オプションpython[w] [-dEhimOQStuUvVWxX?] [-c command | scriptFile | - ] [args]
環境変数
主要な字句エレメントキーワード
識別子(letter | "_") (letter | digit | "_")*
文字リテラルstr (8 ビット/文字の通常の旧式文字列) と unicode (16 ビット/文字の UCS2 文字列)
の 2 つの形式がある。
ブール定数 (2.2.1 以降)
数値
シーケンス
辞書 (マップ)
長さが 0, 1, 2 の 辞書 (
キーは、ハッシュ値取得可能 な型でなければならない。値は、どんな型でもよい。
演算子とその優先順位
基本的な型とその演算子比較 (すべての 型に対して)
None
ブール型 (bool)
数値型浮動小数点数、整数、長整数、10進数
数値型に対する演算子
整数・長整数に対するビット演算子
複素数
数値に関する例外
シーケンス (リスト・タプル・文字列) の演算
変更可能なシーケンス (
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| 演算子 | 結果 | 注 |
|---|---|---|
| len(d) | d の要素数を返す | |
| dict() dict(**kwargs) dict(iterable) dict(d) |
空の辞書を作成する。 キーワード引数 kwargs で初期化した辞書を作成する。 iterable から得られる (キー, 値) の組で初期化した辞書を作成する。 辞書 d のコピーを作成する |
|
| d.fromkeys(iterable, value=None) | iterator から得られるキーを元に辞書を作成し、値を value に設定する | |
| d[k] | d の要素で、キーが k のもの | (1) |
| d[k] = x | d[k] を x にする | |
| del d[k] | d[k] を d から削除する | (1) |
| d.clear() | 全要素を d から削除する | |
| d.copy() | d の(浅い)コピーを返す | |
| d.has_key(k) k in d |
d にキー k があれば True、さもなくば False |
|
| d.items() | d の (キー, 値) というペアを要素とするリストを返す | (2) |
| d.keys() | d のキーのリストを返す | (2) |
| d1.update(d2) | for k, v in d2.items(): d1[k] = v2.4 以降、 キーワード引数 update(**kwargs) と イテレータ update(iterable) も使える |
|
| d.values() | d の値のリストを返す | (2) |
| d.get(k, defaultval) | d から、キー k の値を返す | (3) |
| d.setdefault(k[,defaultval]) | キー k が d にあれば d[k] を返す。さもなくば、 defaultvalを (値に設定した上で) 返す | (4) |
| d.iteritems() | (キー, 値)ペアに対する イテレータ を返す | |
| d.iterkeys() | キー列に対する イテレータ を返す | |
| d.itervalues() | 値列に対する イテレータ を返す | |
| d.pop(k[, default]) | キー k を削除した上で、その値を返す。
そのキーが無ければ、 指定されていれば default を返し、さもなくば KeyError を送出する |
|
| d.popitem() | d の (key, value) ペアのどれかを、削除した上で返す |
TypeError が送出される。KeyError が送出される。 None が返される。 None が返され、マップに追加される。 str 型・unicode 型) の演算str 型と unicode 型の基底クラスはいずれも basestring 型。| 演算子 | 結果 | 注 |
|---|---|---|
| s.capitalize() | s の最初の文字を大文字にした文字列を返す | |
| s.center(width) | width の長さに対し、s を中央寄せした文字列を返す | (1) |
| s.count(sub[ ,start[,end]]) | s 中に部分文字列 sub が出現する回数を返す | (2) |
| s.decode([ encoding[,errors]]) | 指定されたコーデック(文字エンコード)でデコードされたユニコード文字列を返す。
ファイルや、str 型の文字列だけを処理するような入出力関数を使ったの読み込みに有用である。
encode の逆動作である |
(3) |
| s.encode([ encoding[,errors]]) | s をエンコードした str 型の文字列を返す。
(入出力関数が str 型しか処理できないので)出力やファイルへの書き込みを行う際に、
ユニコード文字列を str 型へエンコードするのに良く使われる。
例、 u'légère'.encode('utf8')。
zip (codec 'zip') や uuencode (codec 'uu') など str 型を str 型にエンコードする
のにも使われる。decode の逆動作である |
(3) |
| s.endswith(suffix [,start[,end]]) | s が suffix で終わっていれば True を返す。さもなくば、False を返す |
(2) |
| s.expandtabs([ tabsize]) | s 中のタブをスペースに変換した文字列を返す | (4) |
| s.find(sub[ ,start[,end]]) | s 中で部分文字列 sub が見つかった最小のインデックス値を返す。 見つからなければ -1 を返す | (2) |
| s.index(sub[ ,start[,end]]) | find() と同様だが、見つからなければ ValueError を送出する |
(2) |
| s.isalnum() | s の文字がすべて英数字であれば True を返す。さもなくば False を返す |
(5) |
| s.isalpha() | s の文字がすべて英字であれば True を返す。さもなくば False を返す |
(5) |
| s.isdigit() | s の文字がすべて数字であれば True を返す。さもなくば False を返す |
(5) |
| s.islower() | s の文字がすべて小文字であれば True を返す。さもなくば False を返す |
(6) |
| s.isspace() | s の文字がすべて空白文字であれば True を返す。さもなくば False を返す |
(5) |
| s.istitle() | s の文字がすべてタイトルケース(各単語の始めが大文字)であれば True を返す。
さもなくば False を返す |
(7) |
| s.isupper() | s の文字がすべて大文字であれば True を返す。さもなくば False を返す |
(6) |
| separator.join(seq) | シーケンス seq の文字列を、文字列 separator で区切った形式で連結した文字列を返す。
例、 ",".join(['A', 'B', 'C']) -> "A,B,C" |
|
| s.ljust/rjust/center(width[, fillChar=' ']) | s を左寄せ/右寄せ/中央寄せした、長さが width の文字列を返す | (1), (8) |
| s.lower() | s を小文字に変換した文字列を返す | |
| s.lstrip([chars] ) | s の先頭にある chars (デフォルトは空白文字) を削除する | |
| s.replace(old, new[, maxCount =-1]) | s 中の部分文字列 old の先頭 maxCount 個 (-1のとき制限なし)を new に変換した文字列を返す | (9) |
| s.rfind(sub[ , start[, end]]) | s 中で部分文字列 sub が見つかった最大のインデックス値を返す。 見つからなければ -1 を返す | (2) |
| s.rindex(sub[ , start[, end]]) | rfind() と同様だが、見つからなければ ValueError を送出する |
(2) |
| s.rstrip([chars]) | s の最後にある chars (デフォルトは空白文字) を削除する。e.g.
aPath.rstrip('/') will remove the trailing '/'from aPath if it exists |
|
| s.split([ separator[, maxsplit]]) | s を separator を区切り文字として分解した文字列のリストを返す | (10) |
| s.rsplit([ separator[, maxsplit]]) | splitと同様だが、文字列の最後から分解する |
(10) |
| s.splitlines([ keepends]) | s を改行で分解し、各行からなるリストを返す | (11) |
| s.startswith(prefix [, start[, end]]) | s が prefix で始まっていれば True を返す。さもなくば False を返す。
負値も start と end に使える |
(2) |
| s.strip([chars]) | s の先頭と最後にある chars (デフォルトは空白文字) を削除する | |
| s.swapcase() | s の大文字と小文字を入れ替えた文字列を返す | |
| s.title() | s をタイトルケース化した、つまり各単語の始めを大文字とし残りを小文字とした、文字列を返す。 | |
| s.translate(table [, deletechars]) | s をテーブル table を使って置換した文字列を返す | (12) |
| s.upper() | s を大文字に変換した文字列を返す | |
| s.zfill(width) | 長さ width の、先頭を 0 詰めした文字列を返す |
sys.getdefaultencoding()で、
sys.setdefaultencoding() により変更できる。オプション引数 errors を指定して、
別のエラー処理スキームを設定できる。errors 引数のデフォルトは 'strict'で、
エンコーディング関連エラーはにより ValueError が送出される。他に、'ignore' または
'replace' を指定できる。モジュール codecs を見よ。False が返される。False が返される。None を指定すると、すべての空白文字がセパレータとなる。
maxsplit を指定すると、分解が最大 maxsplit 回まで行われる。 formatString % args --> 文字列を返す
%[flag][width][.precision] formatCodeここで formatCode は c, s, i, d, u, o, x, X, e, E, f, g, G, r, % のどれか (下記参照)。
| フォーマット文字列 | 結果 |
|---|---|
'%3d' % 2 | ' 2' |
'%*d' % (3, 2) | ' 2' |
'%-3d' % 2 | '2 ' |
'%03d' % 2 | '002' |
'% d' % 2 | ' 2' |
'%+d' % 2 | '+2' |
'%+3d' % -2 | ' -2' |
'%- 5d' % 2 | ' 2 ' |
'%.4f' % 2 | '2.0000' |
'%.*f' % (4, 2) | '2.0000' |
'%0*.*f' % (10, 4, 2) | '00002.0000' |
'%10.4f' % 2 | ' 2.0000' |
'%010.4f' % 2 | '00002.0000' |
'%s has %03d quote types.' % ('Python', 2) == 'Python has 002 quote types.'a = '%(lang)s has %(c)03d quote types.' % {'c':2, 'lang':'Python'}
(右側に vars() 関数を使うのも便利である) | formatCode | 意味 |
|---|---|
| d | 符号付き10進整数 |
| i | 符号付き10進整数 |
| o | 符号なし8進数 |
| u | 符号なし10進数 |
| x | 符号なし16進数 (小文字) |
| X | 符号なし16進数 (大文字) |
| e | 浮動小数点数の指数表示 (小文字) |
| E | 浮動小数点数の指数表示 (大文字) |
| f | 浮動小数点数の10進表示 |
| F | 浮動小数点数の10進表示 |
| g | 指数が -4 未満か precision 以上のとき "e"、さもなくば "f" と同じ |
| G | 指数が -4 未満か precision 以上のとき "E"、さもなくば "F" と同じ |
| c | 単一文字 (整数値または単一文字の文字列をとる) |
| r | 文字列 (オブジェクトを repr() を使って変換したもの) |
| s | 文字列 (オブジェクトを str() を使って変換したもの) |
| % | 引数の変換はせず、"%" 文字自体が結果に返る (完全な表記は %%) |
| flag | 意味 |
|---|---|
| # | 「別形式」を使って値変換する |
| 0 | 0 埋めする |
| - | 左寄せする |
| (空白文字) 。正の値(または空白文字)の前に空白文字を置く | |
| + | 正負記号 ("+" または "-") を前に付ける(空白文字フラグより優先される) |
substitute または safe_substitute
メソッドに辞書で指定する(〔テンプレート中に記述した〕キーが〔指定した辞書に〕ない場合、
substitute は KeyError 例外を送出する。
safe_substitute は、〔キーが無いことを〕無視する)。
t = string.Template('Hello $name, you won $$$amount') # (note $$ to literalize $)
t.substitute({'name': 'Eric', 'amount': 100000}) # -> u'Hello Eric, you won $100000'
file 型)。 組み込み関数 open() [推奨]
やそのエイリアス file() から生成される。
他のモジュールの関数からも生成される。| 演算 | 結果 |
|---|---|
| f.close() | ファイル f をクローズする |
| f.fileno() | ファイル f のファイル記述子 (fd) を取得する |
| f.flush() | ファイルの f の内部バッファをフラッシュする |
| f.isatty() | ファイル f が tty (または類似の) デバイスに接続されていれば 1 を、さもなくば 0 を返す |
| f.next() | Returns the next input line of file f, or raises StopIteration when EOF is hit.
Files are their own iterators. next is implicitely called by
constructs like for line in f: print line. |
| f.read([size]) | ファイル f から最大 size バイトを読み込み、文字列オブジェクトを返す。 size を指定しないと、EOF まで読む |
| f.readline() | ファイル f から 1 行読み込む。行の末尾の改行文字は残す。ただし、EOF は残さない。Return '' on EOF. |
| f.readlines() | readline() で EOF まで読み、行のリストを返す |
| f.xreadlines() | ファイル全体をメモリに読み込まないでファイルの各行を読み込むような シーケンス類似のオブジェクトを返す。 2.2 以降では、 for line in f を使う (下記参照) |
| for line in f: do something... | (readline を使って) ファイルの各行をイテレートする |
| f.seek(offset[, whence=0]) | ファイル f の位置を設定する。stdio の fseek() と同じ。 whence == 0 のとき絶対位置指定。 whence == 1 のとき現在位置からの相対指定。 whence == 2 のときファイルの末尾からの指定 |
| f.tell() | ファイル f の現在位置を返す (バイトオフセット) |
| f.truncate([size]) | Truncate f's size. If size is present, f is truncated to (at most) that size, otherwise f is truncated at current position (which remains unchanged). |
| f.write(str) | 文字列をファイル f に書き込む |
| f.writelines(list) | 文字列のリストをファイル f に書き込む。EOL は追加しない |
EOFError IOError set と frozenset (変更不能な set) が追加された
[PEP 218]。
これら set 型は、順番の無いユニークな要素の集合である。要素はハッシュ可能でなければならない。
frozensets 型はハッシュ可能である(つまり、他の set の要素となれる)。
一方、set 型はそうではない。いずれも、イテレート可能 である。sets モジュールにおいて、
Set クラスと ImmutableSet クラスが使用できる。
このモジュールは、2.4 の標準ライブラリに残されており、
組み込み型とあわせ使用できる。| 演算子 | 結果 |
|---|---|
| set/frozenset([iterable=None]) | [using built-in types] Builds a set or frozenset
from the given iterable (default: empty), e.g. set([1,2,3]), set("hello").
|
| Set/ImmutableSet([iterable=None]) | [using the sets module] Builds a Set or ImmutableSet
from the given iterable (default: empty), e.g. Set([1,2,3]).
|
| len(s) | Cardinality of set s. |
| elt in s / not in s | True if element elt belongs / does not belong to
set s. |
| for elt in s: process elt... | Iterates on elements of set s. |
| s1.issubset(s2) | True if every element in s1 is in s2. |
| s1.issuperset(s2) | True if every element in s2 is in s1. |
| s.add(elt) | Adds element elt to set s (if it doesn't already exist). |
| s.remove(elt) | Removes element elt from set s.
KeyError if element not found. |
| s.clear() | Removes all elements from this set (not on immutable sets!). |
| s1.intersection(s2) or s1&s2 | Returns a new Set with elements common to s1 and s2. |
| s1.union(s2) or s1|s2 | Returns a new Set with elements from both s1 and s2. |
| s1.difference(s2) or s1-s2 | Returns a new Set with elements in s1 but not in s2. |
| s1.symmetric_difference(s2) or s1^s2 | Returns a new Set with elements in either s1 or s2 but not both. |
| s.copy() | Returns a shallow copy of set s. |
| s.update(iterable) | Adds all values from iterable to set s. |
mxDateTime
も見よ。
- Module オブジェクト
- Class オブジェクト
- Class instance オブジェクト
- Type オブジェクト (see module: types)
- File オブジェクト (上記参照)
- Slice オブジェクト
- Ellipsis オブジェクト, used by extended slice notation (unique, named
Ellipsis)- Null オブジェクト (unique, named
None)- XRange オブジェクト
- コール可能な 型
- ユーザ定義 (Python で記述)
- User-defined Function オブジェクト
- User-defined Method オブジェクト
- 組み込み (C で記述)
- 組み込み Function オブジェクト
- 組み込み Method オブジェクト
- 内部 型
- Code オブジェクト (byte-compile executable Python code: bytecode)
- Frame オブジェクト (execution frames)
- Traceback オブジェクト (stack trace of an exception)
| 文 | 結果 |
|---|---|
| pass | 何もしない |
| del name[, name]* | name とオブジェクトの結びつけを解除する。オブジェクトは、他から参照されていないなら、 派生的に (また自動的に) 削除されることとなる |
| print[>> fileobject,] [s1 [, s2 ]* [,] | 指定されていれば fileobjectに、さもなくば sys.stdout に出力する。
文が カンマ で終わっていないときは、改行文字が付けられる。Python が対話モードの際は、
print 文は不要で、表現が何か入力されるとその値を、None で無い限り、出力する。 |
| exec x [in globals [, locals]] | 指定した名前空間中の x を実行する。デフォルトは現在の名前空間。 x は、文字列・ファイルオブジェクト・ 関数オブジェクトのどれか。locals には、通常の Python の辞書型以外のマップ型も使える。 |
| callable(value,... [id=value] , [*args], [**kw]) | 関数 callable を引数を与えてコールする。引数は、名前指定で渡せる。また、デフォルト値が設定されていれば、省略できる。
たとえば callable の定義が "def callable(p1=1, p2=2)" のとき、次のようになる。"callable()" <=> "callable(1, 2)"*args は、引数と 位置 でもって対応したタプル。 **kw は、引数と キーワード でもって対応したタプル。 |
| 演算子 | 結果 |
Notes
|
|---|---|---|
| a = b | 基本的な代入 - オブジェクト b をラベル a へ代入するS |
(1)(2)
|
| a += b | a = a + b とほぼ同じ |
(3)
|
| a -= b | a = a - b とほぼ同じ |
(3)
|
| a *= b | a = a * b とほぼ同じ |
(3)
|
| a /= b | a = a / b とほぼ同じ |
(3)
|
| a //= b | a = a // b とほぼ同じ |
(3)
|
| a %= b | a = a % b とほぼ同じ |
(3)
|
| a **= b | a = a ** b とほぼ同じ |
(3)
|
| a &= b | a = a & b とほぼ同じ |
(3)
|
| a |= b | a = a | b とほぼ同じ |
(3)
|
| a ^= b | a = a ^ b とほぼ同じ |
(3)
|
| a >>= b | a = a >> b とほぼ同じ |
(3)
|
| a <<= b | a = a << b とほぼ同じ |
(3)
|
first, second = l[0:2] # first=l[0]; second=l[1] と同じ
[f, s] = range(2) # f=0; s=1 と同じ
c1,c2,c3 = 'abc' # c1='a'; c2='b'; c3='c' と同じ
(a, b), c, (d, e, f) = ['ab', 'c', 'def'] #
a='a'; b='b'; c='c'; d='d'; e='e'; f='f' と同じ
Tip: x,y = y,x は、 x と y を入れ替える
a = b = c = 0
list1 = list2 = [1, 2, 3] # list1 と list2 は 同じ リストになる
| 文 | 結果 |
|---|---|
| if condition: suite [elif condition: suite]* [else: suite] |
一般的な if/else 文 |
| while condition: suite [else: suite] |
一般的な while 文。ループから break で抜けたとき以外は、
else suite を実行する |
| for element in sequence: suite [else: suite] |
sequence に対して、その各要素を element に代入して、繰り返しを行う。
繰り返しを単に何回か行いたいときは、組み込みの range 関数を使う。
ループから break で抜けたとき以外は、
else suite を実行する |
| break | 即座に for または while ループから抜ける |
| continue | 即座に for または while のループの次の繰り返しを行う |
| return [result] | 関数(またはメソッド)から抜け、result を返す
(複数の値を返すときは、 tuple を使う)。
result を指定しなければ、None が返る |
| yield expression | (generator 関数の内部で、
try..finally の外でだけ使う)。 expression を評価した結果を返す |
| 文 | 結果 |
|---|---|
| assert expr[, message] | expr を評価し、偽なら AssertionError をメッセージと共に送出する。
2.3 以前では、__debug__ が 0 のとき使えない |
| try: suite1 [except [exception [, value]: suite2]+ [else: suite3] |
suite1 の文を実行し、例外が送出されたら、except 節で例外マッチングを行う。
exception とマッチするか、exception を指定していないとき、
その節の suite2 を実行する。例外が送出されなければ、 suite1 に続いて
else 節の suite3 を実行する。exception の値は、
変数 value に代入される。exception は例外の タプル でもよい。例、
except(KeyError, NameError), e: print e |
| try: suite1 finally: suite2 |
suite1 の文を実行し、例外が送出されなければ、suite2 を実行する (たとえ
suite1 から return や break , continue で
抜けた場合も)。例外が送出されたら、suite2 を実行し、例外を再送出する |
| raise exceptionInstance | Exception を継承したエラークラスのインスタンスを送出する。(望ましい 例外送出方法) |
| raise exceptionClass [, value [, traceback]] | 指定した例外クラス exceptionClass を、オプション値 value を設定し、送出する。 traceback 引数には、例外のバックトレースを出力するトレースバックオブジェクトを指定する |
| raise | 引数なしの raise 文は、現在の関数内の直近の例外を再送出する |
class TextException(Exception): pass
try:
if bad:
raise TextException()
except Exception:
print 'Oops' # This will be printed because TextException is a subclass of Exception
str() で例外のインスタンスを文字列に変換したものが出力されるException を継承した)StandardError を継承している。sys.path) に設定されたディレクトリに置かなければならない。
2.3 以降、zip ファイルにまとめることも可能 [例、 sys.path.insert(0, "aZipFile.zip")]。__init__.py を含むディレクトリ(空も可)に結びつけるもの。[package.[package...].module.symbol| 文 | 結果 |
|---|---|
| import module1 [as name1] [, module2]* | モジュールをインポートする。モジュールの内容は、 [パッケージ.]モジュール名 を前に付けて参照する。例、
import sys; print sys.argvname1 を指定すると、その名前で module1 を呼べる。 |
| from module import name1 [as othername1][, name2]* | モジュール module から現在の名前空間に指定した名前をインポートする。
from sys import argv; print argvothername1 を指定すると、その名前で name1 を呼べる。 [2.4] from module import names 文で名前のリストをカッコで括れる
(PEP 328). |
| from module import * | module の すべての 名前をインポートする。ただし、"_" で始まるものは除く。
常用しないこと。名前の衝突に注意。
from sys import *; print argvモジュールのトップレベルでのみ使用可能。 module が __all__ 属性を定義しているなら、__all__ にリストされている
名前だけをインポートする。注、 " from package import *" は、パッケージに含まれるモジュールではなく、
そのパッケージの __init__.py ファイルに定義されているシンボルだけをインポートする |
| global name1 [, name2] | 指定した名前を、ローカル (通常は関数) なものでなく、グローバルスコープ (通常はモジュール) のものとする。 たとえば、関数中で global 文がなく、"x" はその関数中で使われていないとする。- "x" を読み込もうとすると、 NameError- "x" に書き込もうとすると、 関数ローカルの "x" を生成 "x" は関数中で定義されていないが、モジュールで定義されている。 - "x" を読み込もうとすると、モジュールから値を取得する - "x" に書き込もうとすると、 関数ローカルの "x" を生成 ただし "x[0]=3" は "x" の検索を行い、ローカルでなくグローバルの "x" を使う |
def funcName ([paramList]):関数オブジェクトを生成し、名前 funcName に代入する。
suiteparamList ::= [param [, param]*]
param ::= value | id=value | *id | **id
return を使うと、関数から戻れる(この場合、None を返す)。
return value とすると value を返して戻る。
複数の値を返すには、return 1,2,3 のように タプル を使う。arg=value を使って デフォルト値
を定義できる(デフォルト値は、関数定義時に評価される) 。foo(x, y=1, s='') のように
変数リストの後ろに記述する。def foo(x, *args): ... を foo(1, 2, 3) とコールすると
args は (2,3) となる。def foo(x, **kwargs): ... を foo(1, y=2, z=3) とコールすると、
kwargs は {'y':2, 'z':3} となる。def foo(x, *args, **kwargs): ... を
foo(1, 2, 3, y=4, z=5) をコールすると、args は (2, 3) となり
kwargs は {'y':4, 'z':5} となる。def f1(x, *args, **kwargs):
f2(*args, **kwargs)
class className [(super_class1[, super_class2]*)]:関数オブジェクトを生成し className という名前に代入する。
suite
suite には、ローカルのクラスメソッドの定義と、クラス属性への代入を記述できる。
class MyClass (class1, class2): ...
class1 と class2 とを継承したクラスオブジェクトを生成する。
その新しいクラスオブジェクトを名前 MyClass に代入する。
class MyClass: ...
基底 クラスオブジェクト (何も継承しないクラス) を生成する。
その新しいクラスオブジェクトを名前 MyClass に代入する。
class MyClass (object): ...
新形式 クラス
(object を継承するクラスは 新形式 クラスとなる。2.2 以降で利用できる)
を生成する。その新しいクラスオブジェクトを名前 MyClass に代入する。
class c (c_parent):
def __init__(self, name):
self.name = name
def print_name(self):
print "I'm", self.name
def call_parent(self):
c_parent.print_name(self)
instance = c('tom')
print instance.name
'tom'
instance.print_name()
"I'm tom"
call_parent メソッドを見よ)。int, float, str,
list, tuple, dict と file は、2.2 以降、
基底クラスオブジェクトを継承したクラスとして動作する。その継承もできる。
x = int(2) # 組み込みのキャスト関数は、基本的型のコンストラクタである
y = 3 # <=> int(3) (リテラルは新しい基本的型のインスタンスである)
print type(x), type(y) # int, int
assert isinstance(x, int) # replaces isinstance(x, types.IntType)
assert issubclass(int, object) # base types derive from base class 'object'.
s = "hello" # <=> str("hello")
assert isinstance(s, str)
f = 2.3 # <=> float(2.3)
class MyInt(int): pass # may subclass base types
x,y = MyInt(1), MyInt("2")
print x, y, x+y # => 1,2,3
class MyList(list): pass
l = MyList("hello")
print l # ['h', 'e', 'l', 'l', 'o']
新しいスタイル
のクラスは object を継承している。
古いスタイル のクラスは継承していない。
class C:
"A description of C"
def __init__(self):
"A description of the constructor"
# etc.
c.__doc__ == "A description of C".
c.__init__.__doc__ == "A description of the constructor"
next() という 1 つだけで、
次の要素を返す、または StopIteration を送出する。obj のイテレータは、組み込み関数
iter(obj) で取得できる。この関数は、obj.__class__.__iter__() をコールする。 __iter__() と next() とを実装した
独自の イテレータを持っている。__iter__() を実装している。辞書型(マップ型)は、そのキーを列挙する。
ファイル型は、その各行を列挙する。 リスト または タプル
を生成できる。例、 list(anIterator)for elt in
collection: if elt in collection:
x,y,z=
collection yield キーワードを使って
コール毎に(1つづつ)値を返す。return または
StopIteration() 送出により、値の列挙の終了を通知する。 generator.next()
とコールすると次の値が得られる。StopIteration が送出されるまで繰り返しコールする。
linkGenerator = (link for link in get_all_links() if not link.followed)
for link in linkGenerator:
...process link...
from __future__ import generators (2.3 以降では不要)
def genID(initialValue=0):
v = initialValue
while v < initialValue + 1000:
yield "ID_%05d" % v
v += 1
return # または: raise StopIteration()
generator = genID() # ジェネレータの生成
for i in range(10): # 10 個の値を生成
print generator.next()
__get__(self, obj, type=None) --> value__set__(self, obj, value) __delete__(self, obj)object の派生クラス)。
[]
staticmethod(f)
とすると、メソッド f(x) がスタティック (unbound) になる。f = classmethod(f) とすると、メソッド
f(theClass, x) がクラスメソッドになる。property の
インスタンスである。プロパティは属性に対する ディスクリプタ プロトコルを実装している。 =>
propertyName = property(fget=None, fset=None,
fdel=None, doc=None)
として、クラスの内部または外部で属性を定義する。定義後は propertyName
または obj.propertyName で属性にアクセスする。__slots__
クラス属性を定義すると、割り当て可能な 属性名を制限できる。
これにより、属性名のミスタイプを防止できる (通常、ミスタイプをしても Python が発見してくれることはなく、
新しい属性が生成される)。
例、 __slots__ = ('x', 'y')@D と記述する。記述位置は、デコレート対象となる関数・メソッドの直前の行である。
@D
def f(): ...
上記は次の記述と同じ。
def f(): ...
f = D(f)
@A
@B
@C
def f(): ...
上記は次の記述と同じ。
f = A(B(C(f)))