print 'Hello YKazu'

('Python', 'Javascript')

Python2

リスト内包表記

# リスト内のyは合わせなければいけない for x in [y * 2 for y in [1, 3, 9]]: print x if節付き # まず、for y in range(10)が評価 # そのyに対して、if y % 2 == 1が評価 # Trueならば、そのyに対して、y + 1が評価 for x in [y + 1 for y in range(10) i…

空のセットを用意

これではエラーになる。 x = {} そこで、set()で空のセットを用意する。 x = set() x.add(2) x.add(5) print(x)

項目7:mapやfilterの代わりにリスト内包表記を使う

a = [1, 2, 3, 4, 5] # リスト内包表記 squares = [x + 3 for x in a] print squares

順序付き辞書

from collections import OrderedDict od = OrderedDict() # キーの挿入順を記録する od['foo'] = 1 od['bar'] = 2 od['hoge'] = 3 od['piyo'] = 4 for value in od.values(): print value

コンテキストマネージャまとめ

28.7. contextlib — with -構文コンテキストのためのユーティリティ — Python 2.7.x ドキュメント blog.amedama.jp python.keicode.com

Pythonのジェネレータ(関数)

ジェネレータとは、retrun式で値を返すのではなく、yield式を呼ぶ関数。 def generator(): print('enter') yield print('exit')

raiseによる意図的な例外throw

import traceback try: raise ValueError('hoge', 'piyo', 'foo', 'bar') except Exception as e: print(traceback.format_exc())

直近例外のtracebackをprintする

import traceback try: 10/0 except Exception as e: # tarceback print(traceback.format_exc()) # おまけ:例外オブジェクトの型 print('{0}'.format(type(e))) # おまけ:例外オブジェクトのargsアトリビュート print('{0}'.format(e.args))

コンテキストマネージャの自作

実装方法A __enter__メソッドを定義 __exit__メソッドを定義 実装方法B @contextlib.contextmanagerデコレータ付きのジェネレータを定義 class MyContextManager: # 必須 def __enter__(self): print '1.enter' return self # 必須 def __exit__(self, exc_t…

スタティックメソッド

class Klass: b = 7 def __init__(self): self.a = 5 @staticmethod def double(c): print(c * 2) # print(self.a) インスタンス変数を参照出来ない # print(cls.b) クラス変数を参照出来ない ins = Klass() # インスタンスから呼び出せる ins.double(3) # 6…

クラスメソッド

class Klass: b = 7 def __init__(self): self.a = 5 def method(self): print(self.a) @classmethod def clsmethod(cls): print(cls.b) # print(cls.a) インスタンス変数を参照するとエラー ins = Klass() # インスタンスメソッドの呼び出し ins.method() #…

残念なPython2のsetterプロパティ

class Man: def __init__(self): self.__x = 10 # ゲッター定義 @property def x(self): return self.__x * 2 # セッター定義 @x.setter def x(self, value): self.__x = value * 3 # デリーター定義 @x.deleter def x(self): del self.__x man = Man() prin…

クラスのメソッド

class PyStash: # コンストラクタ def __init__(self): self.git = '/usr/loca/bin/git' # クラスのメソッド # 最低でも1つの仮引数を持つ(インスタンスを指すselfにする慣例) def clone(self): git = self.getGit() url = self.getURL('ssh') # 実引数は…

subprocess.call()メソッドによるシェルコマンド実行

from subprocess import call import shlex # シェルコマンドをリスト化 args = shlex.split("ls -l {}".format('yoshida.py')) # call()はリストを食べてreturncode属性を返す retcode = call(args)

stringのformat()メソッドによる置換

# Python2.7+ print "<title>{} '{} {}'</title>".format('print', 'Hello', 'Yoshida')

クロージャによる動的な関数定義

def mark_up(tag): # これがクロージャ # 関数の内部で定義された関数が、外側関数のローカル変数を参照しているから。 def closure(content): return '<%s>%s</%s>' % (tag, content, tag) return closure # 動的な関数定義 p = mark_up('p') print p('hello') # <p></p>…

トリプルクォーテーションによる複数行コメント

''' シングル(またはダブル)クォーテーションを3個並べるだけ コメント コメント コメント '''

コンテキストマネージャ

正直なところ、直感的に理解出来なかった。そこで、独断と偏見に基づき、整理する。 コンテキストマネージャとは、 __enter__()メソッドと__exit__()メソッドを少なくとも定義しているクラス 上記以外のメソッドを定義していてもよい withステートメントでイ…

with文

ファイルのオープンとクローズなどをシンプルに書ける。 with open("text.txt", 'w') as file: file.write("Hello Yoshida")

グローバル変数に対する参照と代入

# グローバル変数(関数の外で定義された変数) count = 2 def func(): # 参照ならば何もしなくてよい print count #=> 2 def funk(): # 代入するならば、その前に、global宣言が必要 global count count += 1 print count #=> 3 func() funk() print count …