


Introduction to the use of singleton mode under Python metaclass (code example)
This article brings you an introduction to the use of singleton mode under Python metaclasses (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
1. What is Python metaclass
Reference articleWhat is Python metaclass? Introduction to Python metaclasses
2. What is the singleton pattern
The singleton pattern (Singleton pattern) is a commonly used software design pattern. It contains only one special class called a singleton in its core structure. The singleton mode can ensure that there is only one instance of a class in the system and that the instance is easy to access from the outside world, thereby facilitating control of the number of instances and saving system resources. If you want only one object of a certain class to exist in the system, the singleton pattern is the best solution.
How to ensure that there is only one instance of a class and that this instance is easy to access? Defining a global variable ensures that the object can be accessed at any time, but it does not prevent us from instantiating multiple objects. A better solution is to make the class itself responsible for saving its only instance. This class guarantees that no other instances are created, and it provides a method to access the instance. This is the pattern motivation behind the singleton pattern.
3. Use __new__ to implement singleton
# -*- coding: utf8 -*- class Singleton(object): def __init__(self): print 'entrance of __init__' def __new__(cls, *args, **kwargs): if not hasattr(cls, '_instance'): cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs) return cls._instance if __name__ == '__main__': s1 = Singleton() s2 = Singleton() print s1, s2
In Python, __new__ function is usually used to implement singleton mode. The __new__ function is responsible for constructing objects, similar to the constructor in C. Therefore, in order to make the class only create one instance object, we can overload the behavior of the __new__ function so that it can only construct one instance. In the above code, an _instance attribute is assigned to the Singleton class. If the _instance attribute is None, an instance object is created and the _instance attribute refers to (points to) the object. Otherwise, the object referenced by _instance is returned directly. So s1 and s2 in the code actually refer to the same memory object.
4. Use metaclass __call__ to implement singleton
# -*- coding: utf8 -*- # 单例模式 class SingletonMetaClass(type): def __init__(cls, *args, **kwargs): """ 初始化类 :param args: :param kwargs: """ print 'MetaClass.__init__ called' print cls._instance super(SingletonMetaClass, cls).__init__(*args, **kwargs) def __new__(cls, name, bases, attrs): """ 创建类,负责类的行为和属性的创建 :param name: :param bases: :param attrs: :return: """ print 'MetaClass.__new__ called' # 单例模式 cls._instance = None return type.__new__(cls, name, bases, attrs) # __call__方法其实和类的创建过程和实例化没有多大关系了,定义了__call__方法才能被使用函数的方式执行。 # 被该元类创建的类,属于该元类的一个实例。因此创建其实例的时候,会调用元类的__call_方法 def __call__(cls, *args, **kwargs): """ 使类变为可调用对象 :param args: :param kwargs: :return: """ print 'MetaClass.__call__ called' if cls._instance is None: # 这里会去调用类的__new__函数 cls._instance = super.__call__(SingletonMetaClass, cls).__call__(*args, **kwargs) return cls._instance class A(): __metaclass__ = SingletonMetaClass def __new__(cls, *args, **kwargs): print 'A.__new__ called' return super(A, cls).__new__(cls, *args, **kwargs) if __name__ == '__main__': # 因为类A是SingletonMetaClass的一个实例,执行A()时会调用元类SingletonMetaClass的__call__方法 a1 = A() print a1 a2 = A() print a2
We know that in Python, classes are also objects, and metaclasses are classes that create classes, so classes are actually Instance object of metaclass. In Python, if an object defines the __call__ method, then the object is a callable object, which means that the object can be called by calling a function.
Python's __new__ method is responsible for creating objects, and __init__ method is responsible for initializing objects. In the above code, an object of class A can only be created after class A is created. Therefore, in order to create class A first, the __new__ and __init__ methods of SingletonMetaClass will be executed first. When statement A() is executed to create an object of class A, according to the definition of the __call__ method, since class A is an object of the metaclass SingletonMetaClass, it can be expected that the __call__ method of the metaclass SingletonMetaClass will be called.
MetaClass.__new__ called MetaClass.__init__ called None MetaClass.__call__ called A.__new__ called <__main__.A object at 0x00000000036D2EB8> MetaClass.__call__ called <__main__.A object at 0x00000000036D2EB8>Related recommendations:
Examples of Python using the chain of responsibility pattern and iterator pattern in design patterns
Introduction to the singleton implementation of Python using redis pool
The above is the detailed content of Introduction to the use of singleton mode under Python metaclass (code example). For more information, please follow other related articles on the PHP Chinese website!

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1
Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
