書式化文字列

後ろにtuple作るのがめんどくさかったのだが、求めていたのに近い方法を発見。
http://python.matrix.jp/tips/container/dict.html#id8

name='hoge'
print 'hello %(name)s' % vars()
# "hello hoge"

vars()は知らなかった。
覚えておこう。


ついでに試してみた。

#!/usr/bin/python
# coding: utf-8

# 無駄にデコレータ
def try_except(f):
    def func(*args):
        print "try...",
        try:
            f(*args)
        except Exception, inst:
            print '## Exception ##'
            print '  ', type(inst)     # 例外インスタンス
            print '  ', inst           # __str__ で引数を直接出力できる
    return func

class Hoge(object):
    def __init__(self):
        self.name='hoge'

    @try_except
    def printVars(self):
        print 'hello %(self.name)s' % vars() # 無理w

    @try_except
    def printSelf(self):
        print 'hello %(name)s' % self.__dict__ # vars(self)でも可

class Fuga(object):
    __slots__=['name']
    def __init__(self):
        self.name='fuga'

    @try_except
    def printSelf(self):
        print 'hello %(name)s' % vars(self) # __dict__消滅のため無理

if __name__=='__main__':
    h=Hoge()
    h.printVars()
    h.printSelf()

    f=Fuga()
    f.printSelf()

__slots__使うと__dict__が消滅して使えなくなることと、ネームスペースがネストしているとアクセスできないのは残念(dictだからあたりまえw)。
矢張りrubyの任意の式が突っ込めるのはいけてるな。