初めてのPythonを読んでみる(5)

  • 7章 タプル、ファイルオブジェクト、その他
    • 7.1
      • タプルはリストにかなり似ているが、不変オブジェクトである
      • タプルにはメソッドがない
>>> t = 1,2,3
>>> t
(1, 2, 3)
>>> dir(t)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__str__']
>>> 
>>> l = [1,2,3]
>>> dir(l)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__str__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> 
      • タプル ⇔ リストの相互変換は list / tuple メソッドで行う
      • タプルの必要性 ... 不変性
      • リストはディクショナリのキーになれないが、タプルはなれる
      • これはタプルが不変であることによるものかなぁ
>>> dic = { (1,1) : 'foo', (2,1) : 'bar', (1,2) : 'baz' }
>>> dic
{(1, 2): 'baz', (1, 1): 'foo', (2, 1): 'bar'}
>>> dic[(1,2)]
'baz'
>>> dic.keys()
[(1, 2), (1, 1), (2, 1)]
>>> dic2 = {[1,1] : 'foo'}
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: list objects are unhashable
>>> 
    • 7.2
      • ファイルオブジェクトについて
      • 特筆すべき点なし
    • 7.3
カテゴリ 上書き
数値 数値 不可
文字列 シーケンス 不可
リスト シーケンス
ディクショナリ マップ
タプル シーケンス 不可
ファイル エクステンション
    • 7.4
      • シーケンスオブジェクト的なものを自分で作ることも可能
      • インデクシングは __getitem__, 連結は __add__ を内部的に呼んでいる
      • 可変にしたければ __setitem__ を定義する
    • 7.5
      • copy メソッドや L[:] でのコピーは shallow copy だよ
      • deepcopy する場合は x = copy.deepcopy(y) とする (滅多にないけどね)
    • 7.6
      • 同値性についての比較は == 演算子を使う
      • 同一性についての比較は is 演算子を使う
>>> L1 = [1, [2, 3], (4, 5, 6)]
>>> L2 = [1, [2, 3], (4, 5, 6)]
>>> L1 == L2
True
>>> L1 is L2
False
>>> L1 is L1
True
>>> L3 = L1
>>> L1 == L3
True
>>> L1 is L3
True
>>> 
    • 7.7
      • type() で型がわかる
      • 型の判定には isinstance を使う (Java の instanceof と同じかな)
>>> type([1,2])
<type 'list'>
>>> type((1,2))
<type 'tuple'>
>>> type(1)
<type 'int'>
>>> type('1')
<type 'str'>
>>> type(open('t34.py', 'r'))
<type 'file'>
>>> isinstance(1, int)
True
>>> isinstance('1', str)
True
>>> isinstance('1', int)
False
>>> 
    • 7.8
      • 特になし
    • 7.9
      • 繰り返し演算にご注意
      • 繰り返し、連結、スライシングは shallow copy
>>> L = [1,2,3]
>>> M = L * 4
>>> M
[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> N = [L] * 4
>>> N
[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
>>> L[1] = 100
>>> M
[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> N
[[1, 100, 3], [1, 100, 3], [1, 100, 3], [1, 100, 3]]
>>> 


ビルトインオブジェクトはこれでひとまず終了。次回からはステートメントに関する話題。