Python Code Reading 04 行ってきました。
Python Code Reading 04 に行ってきました。
いつも端っこにいたのですが、今回は、ちょうど夏期休暇を取れていたので、めずらしく前の方に席を陣取れました。
題材はstring.Templateクラスで、講師は伊藤俊輔氏です。
vim使いだーーーー
内容的には、
で、最後のメタクラスの説明がちょっと早くて、
手元でのコードの検証が間に合わなくて、ちょいと置いてかれてしまいました。
もっともっと修行せねば。予習してなかったら、まずかったでしょうな。
でも、string.Templateはさほど使っているわけではないから、
Python力がちょいとパワーアップできたかな。
他の勉強会に比べると、参加=パワーアップな感じがわかりやすくてとても良い。
基礎力が低いからでもあるんだけど。
以下は、走り書きメモ
# テンプレート
s = '%s test percent' print s % 'Python' # => Python test percent s = '%s test %s percent' print s % ('Python', 'aaa') # => Python test aaa percent s = '%(lang)s test %(test)s percent' print s % dict(lang='Python', test='aaa') # => Python test aaa percent
string.Templateのコードサンプル
from string import Template template = Template("this is a ${best} of template ${test} . ${test}check result") print template.substitute({ "test":"aaa", "best":"one of" }) # => this is a one of of template aaa . aaacheck result
キーワード引数を使うパターン
from string import Template template = Template("this is a ${best} of template ${test} . ${test}check result") print template.substitute(best='aaaa', test='xxx')
safe_substituteの方は
置換がまっちしなくてもエラーにならない。
from string import Template template = Template("this is a ${best} of template ${test} . ${test}check result") print template.safe_substitute(best='aaaa')
delimiter変更
from stringbk import Template class Tem(Template): delimiter = '!' template = Tem("this is a !{best} of template !{test}. !{test} check result") print template.substitute({ "test":"aaa", "best":"one of" })
%sを使用した変換処理
valにどんな型のデータが来てもエラーにならずに文字列に変換
return '%s' % (val,)
そういえば、こういう勉強会でとったメモはどうするべきだろう。
講師とかプレゼンする場合はきっちり保管しておくけど、
聞く側である場合は、後でメモを見返すとはあまり考えづらい。
となると、頭に入れたら破棄してしまうのが、いいのだろうか。