シングルトンを書こうと思ったのですが、普通にシングルトンパターンのクラスを書かずに、おかしなコードを書いてしまいました。このコードは投稿しませんが、折角なので晒します。"文字列で表現したクラス名からインスタンスを作る方法"が分かったので、一応収穫ありでした。
。。。何しようとしてたんでしょうね?
# -*- coding: utf-8 -*- import types import weakref """ お題3:シングルトン Pythonでシングルトンを作れ。 """ class Hoge: """ 通常のクラス """ def __init__(self, *args, **kargs): self.param = args def action(self): print self.param def init_singleton(f): """ インスタンス登録オブジェクトを初期化 """ f.instance_dict = {} return f @init_singleton def singleton(class_path, *args, **kargs): """ シングルトンを返す """ signature = ".".join(class_path) if singleton.instance_dict.get(signature, None) is None: tree = globals() classObj = None for name in class_path: leaf = tree.get(name, None) if leaf: if type(leaf) is types.ModuleType: tree = vars(leaf) elif type(leaf) is types.ClassType: classObj = leaf if classObj is None: raise '%s is not found.' % signature singleton.instance_dict[signature] = classObj(args, kargs) return singleton.instance_dict[signature] if __name__ == '__main__': for i in range(2): obj_a = singleton(['Hoge'], 1) obj_b = singleton(['Hoge'], 2) report = (id(obj_a), id(obj_b), obj_a is obj_b) print "Obj-A(id:%s) eq Obj-B(id:%s) ? ... %d" % report del obj_a del obj_b """ # -- use python2.5 -- results -- $ python singleton.py Obj-A(id:3842096) eq Obj-B(id:3842096) ? ... 1 Obj-A(id:3842096) eq Obj-B(id:3842096) ? ... 1 """ """ - シングルトンパターンではないね - GCどうしよう - 弱参照を使いこなせず """

