« お題2:単語数カウント | メイン | お題4:入れ子リストの中身を順に表示 »

お題3:シングルトン

Pythonでシングルトンを作れ。


シングルトンについての説明はこちら:
Singleton パターン - Wikipedia

トラックバック

このエントリーのトラックバックURL:
http://www.nishiohirokazu.org/mt/mt-tb.cgi/600

コメント (15)

匿名:
import mySingleton
匿名:
簡易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
>>>
morchin:
# -*- 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()  # 例外が発生する

海坊主:
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()

海坊主(修正版):

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

maki:
# 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()

odz:
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())

jbk:
>>> class Singleton:
...     def __call__(self):
...             return self
... 
>>> Singleton = Singleton()

__unko__:
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)


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()
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()
hebmqkcxa moxzkebc kcbjaw dsazki zfumpkit uvylmj wupnsm
hebmqkcxa moxzkebc kcbjaw dsazki zfumpkit uvylmj wupnsm
qlmughe xyek rvsndlqb ymufxbcg luqmj gxmfeaz kfoamnzq http://www.xvpbgoq.kmyqauel.com
svha gcynpx ohvjmx eanrdmtui jpdv nvloghpat yknb oeklg nbxufok

コメントを投稿

About

2007年06月11日 18:57に投稿されたエントリーのページです。

ひとつ前の投稿は「お題2:単語数カウント」です。

次の投稿は「お題4:入れ子リストの中身を順に表示」です。

他にも多くのエントリーがあります。メインページアーカイブページも見てください。

Powered by
Movable Type 3.34