Python uses metaclass to implement the Singleton Mode

Source: Internet
Author: User

Python uses metaclass to implement the Singleton Mode

This example describes how Python uses metaclass to implement the Singleton mode. Share it with you for your reference. The specific implementation method is as follows:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

Class Singleton (type ):

Def _ call _ (cls, * args, ** kwargs ):

Print "Singleton call"

If not hasattr (cls, 'instance '):

Cls. instance = super (Singleton, cls). _ call _ (* args, ** kwargs)

Return cls. instance

Def _ new _ (cls, name, bases, dct ):

Print "Singleton new"

Return type. _ new _ (cls, name, bases, dct)

Def _ init _ (cls, name, bases, dct ):

Print "Singleton init"

Super (Singleton, cls). _ init _ (name, bases, dct)

Class Cache (object ):

_ Metaclass _ = Singleton

Def _ new _ (cls, * args, ** kwargs ):

Print "Cache new"

Return object. _ new _ (cls, * args, ** kwargs)

Def _ init _ (cls, * args, ** kwargs ):

Print "Cache init"

Def _ call _ (cls, * args, ** kwargs ):

Print "Cache call"

Print Cache ()

Print Cache ()

Output:

?

1

2

3

4

5

6

7

8

Singleton new

Singleton init

Singleton call

Cache new

Cache init

<__ Main _. Cache object at 0x01CDB130>

Singleton call

<__ Main _. Cache object at 0x01CDB130>

I hope this article will help you with Python programming.

Related Article

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.