65674

python Singleton

<h3>1.  Python __call__ special method practical example</h3>

instantiate a class: x = Foo() is really x = type(Foo).__call__(Foo), where __call__ is defined by the metaclass of Foo

<h3>2.  use call to implement Singleton</h3> class _Singleton(type): """ A metaclass that creates a Singleton base class when called. """ _instances = {} print("_instances") def __call__(cls, *args, **kwargs): ins = cls._instances.get(cls) print("class is:", cls, "instance is:", ins, args, kwargs) if not ins or (hasattr(ins, "_reset") and isinstance(ins, cls) and ins._reset()): cls._instances[cls] = super( _Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] class Singleton(_Singleton('SingletonMeta', (object,), {})): print"Singleton" def __init__(self, *args, **kwargs): print("Singleton __init__", args, kwargs) class Logger(Singleton): print"Logger" def __init__(self, *args, **kwargs): print("Logger __init__") print(args, kwargs) def _reset(self, *args, **kwargs): print("Logger _reset") print(args, kwargs) return True print("Type is:", type(Logger)) print(dir(type(Logger))) l = Logger("hello") l = Logger("world")

Python classmethod()

__new__, __init__, __call__  

<p class="header-title">简述 __init__、__new__、__call__ 方法  

<h3>3.  Creating a singleton in Python</h3> <h4>Method 2: A base class</h4> class Singleton(object): _instance = None def __new__(class_, *args, **kwargs): if not isinstance(class_._instance, class_): class_._instance = object.__new__(class_, *args, **kwargs) return class_._instance class MyClass(Singleton, BaseClass): pass

  

来源:博客园

作者:lvmxh

链接:https://www.cnblogs.com/shaohef/p/11424646.html

Recommend