休憩5分でSingleton@Python

PythonでSingleton. 必要か必要じゃないかはさておき,クックブックに載っていたのを思い出して書く!!

In [1]: class Singleton(object):
   ...:     def __new__(cls, *args, **kargs):
   ...:         if '_instance' not in vars(cls):
   ...:             cls._instance = super(Singleton, cls).__new__(cls, *args, **kargs)
   ...:         return cls._instance
   ...:

In [2]: class Hoge(Singleton):
   ...:     pass
   ...:

In [3]: h1 = Hoge()

In [4]: h2 = Hoge()

In [5]: id(h1)
Out[5]: 18992176

In [6]: id(h2)
Out[6]: 18992176 // 同じだ!

In [7]: class Hige(Hoge):
   ...:     pass
   ...:

In [8]: h3 = Hige()

In [9]: id(h3)
Out[9]: 18992976

In [10]: h1 is h3
Out[10]: False

In [11]: isinstance(h1, Hoge)
Out[11]: True

In [12]: isinstance(h3, Hige)
Out[12]: True

In [13]: isinstance(h3, Hoge)
Out[13]: True

できたっぽいんじゃない. ただ,11~13のチェックの議論は特にしない.なぜならよくわかっていない. たしか,Singletonの間に親クラス(Hoge)があったとしてもー子クラス(Hige)のインスタンスとして返してほしいとかなんとか... あちゃ〜5分こえちゃった..

[Python]

2008/03/25 17:17 | Comments(0)

Comments

Comment Form