Detailed python single-case mode and Metaclass

Source: Internet
Author: User
How to implement the singleton mode

To bind a class instance to a class variable

Class Singleton (object):  _instance = None  def __new__ (CLS, *args):    if not isinstance (Cls._instance, CLS): C4/>cls._instance = Super (Singleton, CLS). __new__ (CLS, *args)    return cls._instance

However, subclasses can override __new__ after inheritance to lose a singleton attribute

Class D (Singleton):  def __new__ (CLS, *args):    return Super (D, CLS). __new__ (CLS, *args)

Using adorners to implement

def Singleton (_CLS):  inst = {}  def getinstance (*args, **kwargs):    if _cls not in inst:      inst[_cls] = _cls (*args, **kwargs)    return INST[_CLS]  return getinstance@singletonclass MyClass (object):  Pass

The problem is that this is not a class but a function, but you can define a class in singleton to solve the problem, but it's a lot of trouble.

Using __metaclass__, this method is the most recommended

Class Singleton (type):  _inst = {}    def __call__ (CLS, *args, **kwargs):    If CLS not in Cls._inst:      cls._inst [CLS] = Super (Singleton, CLS). __call__ (*args)    return Cls._inst[cls]class MyClass (object):  __metaclass__ = Singleton

Metaclass

Meta-class is used to create a class of things, you can simply call the meta-class "class factory", the class is an instance of the Meta class. Type is the inner Jianyuan class of Python, and type is its own meta-class, any class

>>> type (MyClass) type>>> type (type)

In the process of creating class MyClass, Python looks for __metaclass__ in the class's definition, and if so, creates class MyClass with it, or uses the built-in type to create the class. In cases where the class has an inheritance, if the current class is not found, it will continue to look for __metaclass__ in the parent class until none of the parent classes are found to use the type to create the class.
If there are __metaclass__ global variables in the module, the classes will be in the meta-class and try it out for themselves, without any effect.

View the definition of type,

Type (object), the object ' s type
Type (name, bases, Dict), a new type

So by using the type to define a class's meta-class, you can use the function to return an object of the second definition above, or you can inherit the type and override the method in it.

Directly using the type-generated object as a meta-class, the function is to make the property uppercase

def update_ (name, bases, DCT):  attrs = ((name, value) for name, value in Dct.items () if not name.startswith (' __ ')) 
  
   uppercase_attr = {Name.upper (): Value for Name, value in Attrs}  return type (name, bases, Uppercase_attr) class singlet On (object):  __metaclass__ = update_  ABC = 2d = Singleton () Print d.abc# 2
  

In the previous section, the singleton pattern is implemented using class inheritance, and for the first __new__, the type.__new__ is essentially called, but using super can make inheritance clearer and avoid problems

Briefly, __new__ is the method called before __init__, which creates the object and returns it, while __init__ initializes the object with the arguments passed in. Take a look at the two in type and the implementation of __CALL__

Def __init__ (CLS, What, Bases=none, Dict=none): # Known special case of type.__init__    "" "    type (object), the O Bject ' s type    type (name, bases, Dict), a new type    # (copied from class Doc) ""    "    Pass@staticmethod # kn Own case of __new__def __new__ (S, *more): # Real signature unknown; Restored from __doc__  "" "t.__new__ (S, ...)-A new object with type S, a subtype of T" ""  passdef __call__ (SE LF, *more): # Real signature unknown; Restored from __doc__  "" "x.__call__ (...) <==> x (...) "" "  Pass

The first mentioned class is equivalent to the instantiation of the Meta class, and then contact the function used to create the singleton pattern, using the __call__, in fact, with any of the three magic methods can be, to see the use of meta-class method of the invocation of the situation

Class Basic (Type):  def __new__ (CLS, name, bases, newattrs):    print "NEW:%r%r%r%r"% (CLS, name, bases, Newattrs )    return Super (Basic, CLS). __new__ (CLS, name, bases, Newattrs)  def __call__ (self, *args):    print "Call:%r%r "% (self, args)    return super (Basic, self). __call__ (*args)  def __init__ (CLS, name, bases, newattrs):    print" Init:%r%r%r%r "% (CLS, name, bases, Newattrs)    super (Basic, CLS). __INIT__ (name, bases, Dict) class Foo:  __metacl ass__ = Basic  def __init__ (self, *args, **kw):    print "init:%r%r%r"% (self, args, kw) A = foo (' a ') b = foo (' B ')

Results

NEW: 
 
  
   
   ' Foo ' () {' __module__ ': ' __main__ ', ' __metaclass__ ': 
  
   
    
   , ' __init__ ': 
   
    
     
    } Init: 
    
     
      
      ' Foo ' () {' __module__ ': ' __main__ ', ' __metaclass__ ': 
     
      
       
      , ' __init__ ': 
      
       
         }call: 
        
          (' A ',) init: <__main__. Foo object at 0x106fee990> (' a ',) {}call: 
         
           (' B ',) init: <__main__. Foo object at 0x106feea50> (' B ',) {} 
          
         
       
     
      
    
     
   
    
  
   
 
  

The __init__ and __new__ of the Meta class are called only once for the creation of class Foo, and the __call__ method of the meta-class is called each time the instance of Foo is created.

The above is the whole content of this article, the Python singleton model and Metaclass are described, I hope that everyone's learning is helpful.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.