Skip to content

Instantly share code, notes, and snippets.

@wwgist
Created June 11, 2014 14:44
Show Gist options
  • Save wwgist/74de8cd87e1fd8586142 to your computer and use it in GitHub Desktop.
Save wwgist/74de8cd87e1fd8586142 to your computer and use it in GitHub Desktop.
PYTHON: singletons
# -*- 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