Locked History Attachments

Python/CheatSheet

Python チートシート

忘れたときのコピペの為に・・・

制御構文

if

if __condition__:
  # do something
elif __condition2__
  # do something
else:
  # do something

for

for i in [1, 2, 3]:
  print i
# 10回繰り返す
for i in range(10):
  print i

for else

for i in range(10):
  print i

while

while __condition__:
  # do something

else, continue, break

for i in range(10):
  if __condition2__: continue
  if __condition3__: break
  # do something
else:
  # do something

while __condition__:
  if __condition2__: continue
  if __condition3__: break
  # do something
else:
  # do something

elseはループを抜けた時に実行(break時は実行されない)

リスト

定義

array = [1, 2, 3, 4]

リスト内包表記

a = [i*2 for i in range(10)]

ディクショナリ

定義

map = {'key1': value1, 'key2': value2}

dict関数から作成

d = dict(name='apple', price=100)

クラス

クラス宣言とコンストラクタ

class Foo(object):
  def __init__(self):
    pass

空のクラス

class Foo(object):
  pass

クラスの生成

f = Foo()
b = Bar(args)

属性(アトリビュート)の定義

class Foo(object):
  def __init__(self, name='', price=0):
    self.name = name
    self.price = price

クラスメソッドの定義

class Foo(object):
  @classmethod
  def poo(cls):
    pass

比較

class Foo():
  def __eq__(self, other):
    // 同値条件
    return True

モジュール

- クラスや関数の定義されたファイル - ファイル名がモジュール名 - ディレクトリ構造に対応した階層的なモジュール名を使える(パッケージ)

+ foo
   + bar
      + hoge.py 

であれば、foo.bar.hoge がモジュール名。

import

from foo.bar.hoge import do_something, HageClass
do_something()
h = HageClass()

or

from foo.bar import hoge
hoge.do_something()
h = hoge.HageClass()