Python Implementation Singleton mode

Source: Internet
Author: User

Python Implementation Singleton mode

#  using Python to implement a singleton pattern #  method:  using the __new__ method Class singleton (object):     def  __new__ (Cls, *args, **kwargs):         if not  hasattr (cls,  ' _instance '):             cls._instance = object.__new__ (Cls, *args, **kwargs)          return cls._instanceclass testclass (SingleTon):     a = 1#   Method Two:  using adorners (decorator) def singleton1 (Cls, *args, **kwargs):     Instances = {}    def _singleton ():         if cls not in instances:             instances[cls] = cls (*args, **kwargs)          return  instAnces[cls]    return _singleton@singleton1class testclass1 (object):     a = 1#  Shared Properties    properties are shared, but not singleton mode Class singleton3 (object):     _state = {}    def __new__ (Cls, *args, **kwargs):         obj = object.__new__ (Cls, *args, **kwargs)         obj.__dict__ = cls._state         RETURN OBJCLASS TESTCLASS3 (SingleTon3):     a =  1TEST1 = TESTCLASS3 () TEST2 = TESTCLASS3 () test1.a = 2print (test1.a) print ( test2.a) print (test1) print (test2)


This article is from the "Xu Big Tree" blog, please be sure to keep this source http://abelxu.blog.51cto.com/9909959/1967293

Python Implementation 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.