Created
June 11, 2014 14:44
-
-
Save wwgist/74de8cd87e1fd8586142 to your computer and use it in GitHub Desktop.
PYTHON: singletons
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
# При вызове метода __new__ каждый раз возвращается один и тот же объект. | |
# Хранится объект в классовой переменной. | |
# переопределение __new__ (поверхностно) | |
class C(object): | |
instance = None | |
def __new__(cls): | |
if cls.instance is None: | |
cls.instance = super(C, cls).__new__(cls) | |
return cls.instance | |
# через метакласс - перехватываением __call__ (поглубже) | |
class SingletonMeta(type): | |
def __init__(cls, *args, **kw): | |
cls.instance = None | |
def __call__(cls, *args, **kw): | |
if cls.instance is None: | |
cls.instance = super(SingletonMeta, cls).__call__(*args, **kw) | |
return cls.instance | |
class C(object): | |
__metaclass__ = SingletonMeta |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment