Python single-instance mode

Source: Internet
Author: User

single-case mode

As the name implies, there is only one instance, and if it exists, it does not create a

#!/usr/bin/env python
# Encoding:utf-8
class Singleton():
def __new__(Cls,*args,**kwargs) :
if notHasattr (CLS,' _inst '):
cls._inst=Super(SINGLETON,CLS). __new__(Cls,*args,**kwargs)
returnCls._inst
class A(Singleton):
def __init__(Self, s=none) :
SuperA Self). __init__()
Self. s=s
if__name__==' __main__ ':
A=a ()
B=a ()
Print (a)
Print (b)

The output can be seen as instance addresses of instances A and B

<__main__.A object at 0x02742810>
<__main__.A object at 0x02742810>

By using the __new__ method, an instance of the class is bound to the Class property _inst when it is created. If Cls._inst is none, the description class is not instantiated, instantiates, and binds the instance to Cls._inst, returning the instance that was created the first time each time it is instantiated. Note When deriving subclasses from Singleton, do not overload new.

Python single-instance 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.