Python object-oriented, single-instance mode

Source: Internet
Author: User

@ (python path) [object-oriented, Singleton mode]

[TOC]

Simple Interest Mode

Singleton mode: is a common software design pattern, the main purpose of this mode is to ensure that only one instance of a class exists. a singleton can come in handy when you want the entire system to have only one instance of a class.
The characteristics of the singleton mode:

  • First, a class can have only one instance;
  • Second, he must create this instance on his own;
  • Thirdly, it must provide this example to the whole system.
Ways to implement the simple interest pattern
  • Using modules
  • Using __new__
  • Using adorners (decorator)
  • Using meta-classes (Metaclass)
Using modules

When the module is first imported, the. pyc file is generated, and the. pyc file is loaded the second time it is imported, and the code is not executed again. Therefore, we only get a singleton pattern.
For example:

#mysingleton.pyclass MySingleton(object):    def foo(self):        print("My singleton"= MySingleton()
#main.pyfromimport mysingletonmysingleton.foo()
Using __new__
in order for a class to appear only one instance, we can use new to control the creation of the instance, with the following code:
class Singleton(object):    =None    def__new__***kw):        ifnot cls._instance:            =super(Singleton, cls).__new__***kw)              #这里的super的意思是,该怎么走就怎么走。        return cls._instance  class MyClass(Singleton):      =1

In the above code, we associate an instance of the class with a class variable _instance, and if Cls._instance is None then create the instance, or return the cls._instance directly.
Status of implementation:

>>> one = MyClass()>>> two = MyClass()>>> one == twoTrue>>> one is twoTrue>>> id(one), id(two)(4303862668, 4303862668)
Using adorners

We know that adorners (decorator) can dynamically modify the functionality of a class or function. Here, we can also use adorners to decorate a class so that it can generate only one instance, the code is as follows:

from  functools import  wraps def  Singleton (CLS): Instances =  {}  @wraps  (CLS) def  getinstance (*  ar GS, **  Kwargs): if  cls not   In  Instances:instances[cls] =  cls (*  args, **  Kwargs) return  instances[cls] return  getinstance
    
      @singleton  
     class  MyClass (
     object ): a 
     =  
     1  
     

Above, we define an adorner singleton, which returns an intrinsic function getinstance that determines whether a class is in the dictionary instances, and if not, the CLS as Key,cls (*args, **kw) as Value is stored in instances, otherwise, return directly to Instances[cls].

Using Metaclass

A meta-class (Metaclass) can control the creation of a class, and it mainly does three things:

  • Block creation of classes
  • Modifying the definition of a class
  • Returns the Modified class

To implement the code for a singleton pattern with a meta class:

class  Singleton ( type ): _instances =  {} def  __call__  (CLS, *  args, **  Kwargs): if  cls not  in  Cls._instances:cls._instances[cls] =  super  (Singleton, CLS). __call__         (*  args, **  Kwargs) return  cls._instances[cls] # Python2  # class MyClass (object):  # __metaclass__ = Singleton  # Python3  class  MyClass (Metaclass=  Singleton): pass  

Advantages

  • First, instance control
    Singleton mode organizes other objects to instantiate copies of their own singleton objects, ensuring that unique instances are accessible to all objects.
  • Second, flexibility
    Because classes control the instantiation process, classes can flexibly change the instantiation process.
    Disadvantages
  • First, the cost
    Although the amount of overhead is small, there is still some overhead required to check for an instance of the class every time an object request is checked. This problem can be resolved by using static initialization.
  • Ii. possible confusion of development
    When using singleton objects, especially those defined in a class library, the developer must remember that the object cannot be instantiated using the New keyword. Because the library source code may not be accessible, the application developer may accidentally discover that they are directly instantiating this class.
  • Third, the object life cycle
    The problem of deleting an object cannot be resolved. In a language that provides memory management, such as a. NET framework-based language, only a singleton class can cause an instance to be deallocated because it contains a privatized reference to that instance. In some languages, such as C + +, other classes can delete object instances, but this causes a floating reference to occur in the instance class.
Supplemental: meta-Class (Metaclass)

Comments:
The class is also an object, so long as you use the keyword Class,python The interpreter will create an object when it executes.
For example:

class Foo(object):    pass

This code will be created in memory in an object named Foo. this object (class) itself has the ability to create class objects (class strength), and that is why he is a class. However, he is essentially still an object, so you can manipulate it as follows

  • Copy it to a variable
  • Copy
  • Add properties to it
  • Pass him as a function
>>> classFoo (Object):...Pass...>>> Print(Foo)# Print a class, because he is an object<class ' __main__. Foo '>##########################################>>> defEcho (o): ...Print(o) ...>>>Echo (Foo)# Pass a class as a parameter to a function<class ' __main__. Foo '>#########################################>>>Foo.new_attribute= "foo"   # Increase the properties of the class>>> Print(hasattr(Foo,"New_attribute"))True>>> Print(Foo.new_attribute) Foo##########################################Myfoo=FooPrint(Myfoo ())# You can assign a class to a variable

Dynamically creating classes
Because classes are also objects, they can be created dynamically at run time, just like any other object. First, you can create a class in a function, using the class keyword.

defChoose_class (name):ifName== ' foo ':classFoo (Object):Pass        returnFoo# Returns a class, not an instance of a class    Else:classBar (Object):Pass         returnBar MyClass=Choose_class (' foo ')Print(MyClass)the # function returns a class, not an instance of the class# <class ' __main__.choose_class.<locals>. Foo ' > Print(MyClass ())# You can create a class instance from this class, which is the object# <__main__.choose_class.<locals>. Foo object at 0x00000000021e5cf8>

The type dynamically creates the class.
Type can work like this

type(类名, 父类的元组(针对继承的情况,可以为空),包含属性的字典(名称和值))

For example, the following code:

class MyTypeClass(object):    pass

Can be created in the form of type:

>>>=type("MyTypeClass",(),{})  # 返回一个对象>>>print(MyTypeClass)<class'__main__.MyTypeClass'>>>>print(MyTypeClass())  # 创建一个类的实例<object0x0542A590>

The type receives a dictionary to define properties for the class, so:

class Foo(object):    =True

Can be translated as:

=type("Foo",(),{"bar":True})

Foo can also be used as a normal class:

class Foo(object):    =True>>>print(Foo)<class'__main__.Foo'>>>>print(Foo.bar)True>>>

can also inherit

class FooTwo(Foo):    pass

Can also be written as:

class Foo(object):    =True=type("FooTwo",(Foo,),{})>>>print(FooTwo)<class'__main__.FooTwo'>>>>print(FooTwo.bar)     # bar属性由Foo继承而来True

In Python, classes are also objects, and you can create classes on the fly. This is what Python does behind the scenes when you use the keyword class, which is achieved through the Meta class.
What is a meta-class, which is what is used to create classes. A meta-class is a class of classes. The
function type is actually a meta-class. The type is the meta-class that Python uses to create all the classes behind. The
type is the class that creates the class object, which you can see with the __class__ property.
Everything in Python, notice that everything here is an object. including integers, strings, functions, and classes, all of them are objects, and they are all created from a class.

=35print(age.__class__)    #<class 'int'>='bob'print(name.__class__)   #<class 'str'>def foo():    passprint(foo.__class__)    #<class 'function'>class Bar(object):    pass= Bar()print(b.__class__)      #<class '__main__.Bar'>

Now, what is the __class__ attribute for any one __class__?

print(age.__class__.__class__)  #<class 'type'>print#<class 'type'>print(foo.__class__.__class__)  #<class 'type'>print(b.__class__.__class__)    #<class 'type'>

Therefore, a meta-class is something that creates objects of this class.
Type is the Python Jianyuan class, and of course you can create your own meta-class.
__metaclass__ Property
You can add the __metaclass__ property to a class when you write it.

class Foo(object):    = something...

Python will look for the __metaclass__ attribute in the class definition, and if found, Python will use it to create the class Foo, and if not found, it will use the built-in type to create the class.

Note: This piece of blog to learn from netizens a blog, address can not find.

Python object-oriented, singleton mode

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.