


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!

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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),

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

WebStorm Mac version
Useful JavaScript development tools

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.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft