こしごぇ(B)

旧:http://d.hatena.ne.jp/koshigoeb/

Python 再入門(3.1)

参考書籍

パーフェクトPython (PERFECT SERIES 5)

パーフェクトPython (PERFECT SERIES 5)

The Zen of Python

  • Beautiful is better than ugly.
  • Explicit is better than implicit.
  • Simple is better than complex.
  • Complex is better than complicated.
  • Flat is better than nested.
  • Sparse is better than dense.
  • Readability counts.
  • Special cases aren't special enough to break the rules.
  • Although practicality beats purity.
  • Errors should never pass silently.
  • Unless explicitly silenced.
  • In the face of ambiguity, refuse the temptation to guess.
  • There should be one-- and preferably only one --obvious way to do it.
  • Although that way may not be obvious at first unless you're Dutch.
  • Now is better than never.
  • Although never is often better than right now.
  • If the implementation is hard to explain, it's a bad idea.
  • If the implementation is easy to explain, it may be a good idea.
  • Namespaces are one honking great idea -- let's do more of those!

Python の基本

  • __name__ 変数
  • input()
  • print()
  • docstring
  • global, nonlocal
  • 定数はない
  • GC はリファレンスカウンタ式

型とリテラル

  • 論理型: True, False
  • 数値型
    • int
      • Python3 では Python2 の long と同等
      • Python3 では 整数同士の除算の結果に浮動小数点数を使う
    • complex
    • モジュール: math, cmath, numbers, fractions, decimal
  • シーケンス
    • 文字列(str)、バイト列(bytes)
      • Python3 ではスクリプトファイルは UTF-8 で記述されている事を想定している
      • immutable
    • バイト配列型(bytearray)
      • mutable なバイト列
    • リスト(lists)
      • mutable
    • タプル(tuples)
      • immutable
  • 集合(set)
    • ユニークなリストで順序は保持されない
    • add, remove
    • イテレーション
    • union
    • intersection
    • difference, symmetric_difference
    • issubset, isuperset, disjoint
  • 辞書型
    • 存在しないキーを指定すると例外
    • 順序は保証されない
  • None 型

制御構文

条件文

    • None
    • False
    • ゼロとして認識出来る数値型(0, 0.0, 0j, ...)
    • 空のシーケンス([], (), ...)
    • 空のマップ型({})
    • 空のセット(set())
    • __nonzero__ メソッドが実装されているクラスで False を返すもの
    • __len__ メソッドが実装されているクラスで 0 を返すもの
if x:
    ...
elif y:
    ...
else:
    ...
  • and, or, not

比較演算子

  • >, <, ==, is

ループ

  • for i in [1, 2, 3]:
    • else
      • ループが終わったとき、ループしなかったときに実行される
      • break でぬけたときは実行されない
  • while
    • else
      • for 同様

リスト内包表記

  • 簡潔に記述できる
  • 実行コストを軽減できる

リスト内包表記

>>> [x ** 2 for x in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

セット内包表記

>>> {x ** 2 for x in range(1, 11)}
set([64, 1, 36, 100, 81, 9, 16, 49, 25, 4])

辞書内包表記

>>> {x * 2 : x ** 2 for x in range(1, 11)}
{2: 1, 4: 4, 6: 9, 8: 16, 10: 25, 12: 36, 14: 49, 16: 64, 18: 81, 20: 100}

例外処理

  • try, except
>>> try:
...     10/0
... except Exception as e:
...     print e
...
integer division or modulo by zero
  • else ** try ブロックで例外が発生しなかった場合に実行される
  • finally ** try ブロックで例外が発生したかにかかわらず実行される
>>> def test(x):
...     try:
...         10 / x
...     except Exception as e:
...         print x
...     else:
...         print 'success'
...     finally:
...         print 'fin.'
...
>>> test(1)
success
fin.
>>> test(0)
0
fin.
  • raise
  • assert
  • 例外オブジェクトの __context__

with

with open('test.txt', 'a') as f:
    f.write('test')
  • with ブロックに入るときにコンテキストマネージャ(ContextManager)の __enter__ メソッドを呼び出し、出るときに __exit__ メソッドを呼び出す
  • contextlib の closing を使うと close してくれる
from contextlib import closing
with closing(open('test.txt', 'a')) as f:
    f.write('test')
  • open の場合はそれ自体がコンテキストマネージャとして使えるため、closing を使う必要は無い
  • ジェネレータと contextlib の contextmanager デコレータを使う方法もある