Python Singleton mode instance

Source: Internet
Author: User
This article mainly introduces the Python Singleton mode, analyzes the concept, implementation and usage of Singleton mode in the form of instances, and has paid attention to the relevant issues, for more information about the Python Singleton mode, see the following example. We will share this with you for your reference. The details are as follows:

Singleton mode:Make sure that a class has only one instance and provides a global access point to it.

There is only one way to implement a class:

1. make a global variable so that an object is accessed, but it cannot prevent external instantiation of multiple objects.

2. let the class itself save its unique instance. this class can ensure that no other instance can be created.

Singleton mode for multithreading:Lock-double lock

Hunger examples:The class is instantiated (static initialization) when it is loaded ). Its advantage is that it avoids the security problem of multi-thread access, and its disadvantage is that it occupies system resources in advance.

Lazy singleton type:The instance is instantiated only when it is referenced for the first time. Avoid occupying system resources at the beginning, but there are multi-threaded access security issues.

Instance:

# Encoding = UTF-8 # single-instance mode def PrintInfo (info): # print unicode (info, 'utf-8 '). decode ('gbk') print info. decode ('utf-8 '). encode ('utf-8') import threading # Singleton (): instance = None mutex = threading. lock () def _ init _ (self): pass @ staticmethod def GetInstance (): if (Singleton. instance = None): Singleton. mutex. acquire () if (Singleton. instance = None): PrintInfo ('initialize instance') Singleton. instance = Singleton () else: PrintInfo ('Singleton instantiated ') Singleton. mutex. release () else: PrintInfo ('Singleton instantiated ') return Singleton. instancedef clientUI (): Singleton. getInstance () Singleton. getInstance () Singleton. getInstance () returnif _ name __= = '_ main _': clientUI ();

Result:

Initialize instance Singleton has been instantiated

The append explanation @ staticmethod mentioned classmethod in Python should mention staticmethod, not because of the relationship between the two, but to differentiate users so that they can write code more clearly. In C ++, we understand that a function directly accessed by class name is called a static function of the class, that is, a static modified function. in C ++, classmethod and staticmethod are concepts. So what is the difference between the two in python? Let's take a look at how the two are declared in python code.

Class MyClass :... @ classmethod # classmethod modifier def class_method (cls, arg1, arg2 ,...) :... @ staticmethod # staticmethod modifier def static_method (arg1, arg2 ,...) :...

For the classmethod parameter, the class name needs to be passed implicitly, while the staticmethod parameter does not need to pass the class name. In fact, this is the biggest difference between the two.

Both can be called through the class name or class instance object, because the emphasis is on classmethod and staticmethod, so it is best to use the class name when writing code, good programming habits.

Staticmethod is set to be defined in the class. it is rarely used in this way. it can be replaced by a module-level function. Since we want to define it in a class, the author must consider it.

For classmethod, you can use subclasses to redefine it.

When it comes to class-level functions, it also mentions class-level variables.

class MyClass: i = 123 # class-level variable def __init__(self): self.i = 456 # object-level variable ...

In order to clearly distinguish the above two I, the best way is to consider that everything in python is an object, so I = 123 belongs to class object, and I = 456 belongs to class instance object.

For more articles about Python Singleton mode instances, refer to PHP Chinese network!

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.