« お題2:単語数カウント | メイン | お題4:入れ子リストの中身を順に表示 »
Pythonでシングルトンを作れ。
シングルトンについての説明はこちら: Singleton パターン - Wikipedia
投稿者: 西尾泰和 日時: 2007年06月11日 18:57 | パーマリンク
このエントリーのトラックバックURL: http://www.nishiohirokazu.org/mt/mt-tb.cgi/600
import mySingleton
投稿者: 匿名 | 2007年06月13日 01:14
日時: 2007年06月13日 01:14
簡易singleton >>> class Hoge: ... pass ... >>> h = Hoge() >>> del Hoge >>> h2 = Hoge() Traceback (most recent call last): File "", line 1, in ? NameError: name 'Hoge' is not defined >>>
投稿者: 匿名 | 2007年06月13日 14:47
日時: 2007年06月13日 14:47
# -*- coding: utf-8 -*- def singleton(obj, inst={}): """同一クラス名のオブジェクトが既に登録されていれば例外を発生させる""" assert obj.__class__ not in inst, '%s is already instantiated.' % obj.__class__ inst[obj.__class__] = True class Foo: """任意のクラス""" def __init__(self): singleton(self) # ここでクラス名を登録 if __name__ == '__main__': # 参考URL: http://newworld.ddo.jp/doc/python-iaq-ja/index_html Foo() Foo() # 例外が発生する
投稿者: morchin | 2007年06月13日 15:05
日時: 2007年06月13日 15:05
class Singleton: __instances = {} __creations = set() def __init__(self): if self.__class__ not in self.__creations: raise RuntimeError("must call instance()") @classmethod def instance(cls): Singleton.__creations.add(cls) try: instance = Singleton.__instances.get(cls, None) if instance is None: Singleton.__instances[cls] = instance = cls() return instance finally: Singleton.__creations.remove(cls) class Foo(Singleton): def __init__(self): Singleton.__init__(self) class Boo(Singleton): def __init__(self): Singleton.__init__(self) print Foo.instance() print Boo.instance() print Foo.instance() print Boo.instance()
投稿者: 海坊主 | 2007年06月14日 19:09
日時: 2007年06月14日 19:09
class Singleton: __instances = {} __creations = set() def __init__(self): if self.__class__ not in self.__creations: raise RuntimeError("must call instance()") @classmethod def instance(cls): instance = Singleton.__instances.get(cls, None) if instance is None: Singleton.__creations.add(cls) try: Singleton.__instances[cls] = instance = cls() finally: Singleton.__creations.remove(cls) return instance class Foo(Singleton): def __init__(self): Singleton.__init__(self) class Boo(Singleton): def __init__(self): Singleton.__init__(self) print Foo.instance() print Boo.instance() print Foo.instance() print Boo.instance() Foo() # exception
投稿者: 海坊主(修正版) | 2007年06月14日 19:13
日時: 2007年06月14日 19:13
# vim: fileencoding=utf-8 """ class Fooは宣言した段階で(メタクラスによって)インスタンス化されるため, Foo自体がインスタンスになる. クラスFooにアクセスするには、Foo.__class__としなければならない. Foo() == Foo.__call__() のため、常に、Foo.__singleton__が返る. (一度目の__call__呼び出し時に引数を__init__を呼び出す). """ __all__ = ['MetaSingleton'] class MetaSingleton(type): """ >>> class Hoge(object): ... pass >>> Hoge() is Hoge() False >>> class Foo(object): ... __metaclass__ = MetaSingleton ... def __init__(self, name=None): ... self.name = name ... @classmethod ... def hello(cls): ... print "Hello" >>> f = Foo(name="spam") >>> f.name 'spam' >>> f = Foo(name="hoge") >>> f.name 'spam' >>> Foo.__class__.hello() Hello >>> f is Foo is Foo() is Foo() is Foo.__singleton__ True """ def __new__(cls, name, bases, attrs): new_cls = type.__new__(cls, name, bases, attrs) def __call__(self, *args, **kwargs): if hasattr(self, '__singleton__'): return self.__singleton__ self.__init__(*args, **kwargs) self.__singleton__ = self return self.__singleton__ new_cls.__call__ = __call__ __init__ = new_cls.__init__ del new_cls.__init__ obj = new_cls() # instance create new_cls.__init__ = __init__ return obj if __name__ == '__main__': import doctest doctest.testmod()
投稿者: maki | 2007年06月17日 02:03
日時: 2007年06月17日 02:03
class Singleton(object): _instances = dict() def __new__(clazz, *args, **kwargs): if clazz not in clazz._instances: clazz._instances[clazz] = object.__new__(clazz, *args, **kwargs) return clazz._instances[clazz] class DerivedSingleton(Singleton): pass if __name__ == '__main__': print id(Singleton()) print id(Singleton()) print id(DerivedSingleton()) print id(DerivedSingleton())
投稿者: odz | 2007年06月20日 16:31
日時: 2007年06月20日 16:31
>>> class Singleton: ... def __call__(self): ... return self ... >>> Singleton = Singleton()
投稿者: jbk | 2007年06月23日 20:34
日時: 2007年06月23日 20:34
class Singleton: __ins = None; def __init__(self): if Singleton.__ins == None: Singleton.__ins = self; else: raise RuntimeError("instance あり") class SingletonBuilder: __sin = None; def getInstance(self): try: SingletonBuilder.__sin = Singleton(); except: None; return SingletonBuilder.__sin; a1 = SingletonBuilder().getInstance(); a2 = SingletonBuilder().getInstance(); print (a1==a2)
投稿者: __unko__ | 2007年06月25日 14:51
日時: 2007年06月25日 14:51
class Singleton(object): __instances = {} def __new__(cls): if cls in cls.__instances: raise RuntimeError('Already Singleton Instance.') return object.__new__(cls) def __init__(cls): raise RuntimeError('Already Singleton Instance.') @classmethod def __pass(cls): pass @classmethod def instance(cls): if not cls in cls.__instances: init = cls.__init__ cls.__init__ = cls.__pass cls.__instances[cls] = cls() cls.__init__ = init return cls.__instances[cls] def debug(self): print self.__instances class Hoge1(Singleton): def get_name(self): return 'hoge1' class Hoge2(Singleton): def get_name(self): return 'hoge2' def main(): # RuntimeError test... #hoge = Hoge1() # Instance test... hoge1_1 = Hoge1.instance() print hoge1_1.get_name() hoge2_1 = Hoge2.instance() print hoge2_1.get_name() hoge1_2 = Hoge1.instance() print hoge1_2.get_name() if __name__ == '__main__': main()
投稿者: Isoparametric | 2007年06月28日 11:50
日時: 2007年06月28日 11:50
投稿者: Isoparametric | 2007年06月28日 11:51
日時: 2007年06月28日 11:51
hebmqkcxa moxzkebc kcbjaw dsazki zfumpkit uvylmj wupnsm
投稿者: pyxtio wehrlv | 2007年09月26日 06:08
日時: 2007年09月26日 06:08
投稿者: pyxtio wehrlv | 2007年09月26日 06:09
日時: 2007年09月26日 06:09
qlmughe xyek rvsndlqb ymufxbcg luqmj gxmfeaz kfoamnzq http://www.xvpbgoq.kmyqauel.com
投稿者: duoljh yimfego | 2007年09月26日 06:09
svha gcynpx ohvjmx eanrdmtui jpdv nvloghpat yknb oeklg nbxufok
投稿者: sfuy qcabxt | 2007年09月26日 06:10
日時: 2007年09月26日 06:10
名前:
メールアドレス:
URL:
この情報を登録しますか?
コメント:
2007年06月11日 18:57に投稿されたエントリーのページです。
ひとつ前の投稿は「お題2:単語数カウント」です。
次の投稿は「お題4:入れ子リストの中身を順に表示」です。
他にも多くのエントリーがあります。メインページやアーカイブページも見てください。
コメント (15)
投稿者: 匿名 | 2007年06月13日 01:14
日時: 2007年06月13日 01:14
投稿者: 匿名 | 2007年06月13日 14:47
日時: 2007年06月13日 14:47
投稿者: morchin | 2007年06月13日 15:05
日時: 2007年06月13日 15:05
投稿者: 海坊主 | 2007年06月14日 19:09
日時: 2007年06月14日 19:09
投稿者: 海坊主(修正版) | 2007年06月14日 19:13
日時: 2007年06月14日 19:13
投稿者: maki | 2007年06月17日 02:03
日時: 2007年06月17日 02:03
投稿者: odz | 2007年06月20日 16:31
日時: 2007年06月20日 16:31
投稿者: jbk | 2007年06月23日 20:34
日時: 2007年06月23日 20:34
投稿者: __unko__ | 2007年06月25日 14:51
日時: 2007年06月25日 14:51
投稿者: Isoparametric | 2007年06月28日 11:50
日時: 2007年06月28日 11:50
投稿者: Isoparametric | 2007年06月28日 11:51
日時: 2007年06月28日 11:51
投稿者: pyxtio wehrlv | 2007年09月26日 06:08
日時: 2007年09月26日 06:08
投稿者: pyxtio wehrlv | 2007年09月26日 06:09
日時: 2007年09月26日 06:09
投稿者: duoljh yimfego | 2007年09月26日 06:09
日時: 2007年09月26日 06:09
投稿者: sfuy qcabxt | 2007年09月26日 06:10
日時: 2007年09月26日 06:10