2- object-oriented class is instantiated with singleton

A class instance of a process object

class Foo(object):
    def __init__(self,x):
        self.x = x  
f = Foo(x)       
>>>Foo.__class__
<class 'type'>

So Foois the type typeof an object, Fooa class, but classes in Python is an object! Classes, functions, methods, and examples are objects, and whenever you put a pair of brackets behind their names, they will call their __call__methods. FooIs the type typeof an object and the call __call__returns a Fooclass object

Conventional instantiation of a class is roughly equivalent to:

def __call__(obj_type, *args, **kwargs):
    obj = obj_type.__new__(*args, **kwargs)
    if obj is not None and issubclass(obj, obj_type):
        obj.__init__(*args, **kwargs)
    return obj

__new__Methods for the object allocated memory space, building it into an "empty" object and __init__method is called to initialize it.
In general:

  1. Foo(*args, **kwargs)Equivalent toFoo.__call__(*args, **kwargs)
  2. Since it Foois an typeinstance of Foo.__call__(*args, **kwargs)the actual call istype.__call__(Foo, *args, **kwargs)
  3. type.__call__(Foo, *args, **kwargs)Call type.__new__(Foo, *args, **kwargs), then returns an object.
  4. objFollowed by a call obj.__init__(*args, **kwargs)is initiated.
  5. objIt is returned.

Details: https: //www.jianshu.com/p/f63ad9d550f1

Second, singleton

Definition: to ensure that only one instance of a class, and examples of their own and provide the example of the whole system

Scene: 1 requires frequent instantiation and destruction of objects;.

2. stateful tools Objects

3. frequent access to the database or file objects

For example: Designing multi-threaded thread pool

Website counter, are generally single-case model to achieve, otherwise difficult to synchronize.

Connection pool database design are generally single embodiment mode.

Related content: https: //www.cnblogs.com/restartyang/articles/7770856.html

Advantages :
a single embodiment mode 1. In the example, the activity of a single embodiment only one instance of singleton instances of all classes obtained are the same. This prevents other objects instantiated own, to ensure that all have access to an instance of an object
2. The single mode embodiment having a certain flexibility, their class to instantiate the control process, based on a corresponding change in the stretching process is instantiated sex.
3. provides controlled access to the only instance.
4. Since there is only one object in the system memory, it is possible to save system resources, when the object frequently created and destroyed in a single embodiment mode will undoubtedly improve system performance.
5. To allow a variable number of instances.
6. Avoid multiple assignment of shared resources.
Disadvantages:
1. Not to change the subject, if the same type of object variations always occur in different use-case scenario, a single case will cause erroneous data can not be saved in another state.
2. Since no simple interest model abstraction layer, thus expanding the singleton class have great difficulty.
3. The functions of singleton class too heavy, contrary to the "single responsibility principle" to some extent.
4. abuse singleton will bring some negative issues, in order to save resources such as database connection pool object as a singleton class design, may lead to excessive shared object connection pool connection pool program appears overflow; if instantiated objects a long time without being used, the system will be considered garbage to be collected, which will result in the loss of the object's state.

Create a singleton

Method 1: metaclass

class Singleton(type):
    def __init__(cls, name, bases, dict):
        super(Singleton, cls).__init__(name, bases, dict)
        cls.instance = None 

    def __call__(cls,*args,**kw):
        if cls.instance is None:
            cls.instance = super(Singleton, cls).__call__(*args, **kw)
        return cls.instance

class MyClass(object,metaclass=Singleton):
    pass
'''
#python2中
class MyClass(BaseClass)
    __metaclass__ = Single   #属性 __metaclass__,其用来表示该类由谁来实例化创建
    
'''

Method 2: decorators

def singleton(class_):
    instances = {}
    def getinstance(*args, **kwargs):
        if class_ not in instances:
            instances[class_] = class_(*args, **kwargs)
        return instances[class_]
    return getinstance

@singleton
class MyClass(object):  #python2中: class MyClass(BaseClass):
    pass
#经过装饰器修饰,增加了判断的功能,如果该类实例化过,实例的对象就会被添加在instance字典中,再次实例化,将从字典中返回

More ways to: https: //stackoverflow.com/questions/100003/what-are-metaclasses-in-python

Guess you like

Origin www.cnblogs.com/notfind/p/11568405.html