Singleton mode "Python"

Source: Internet
Author: User

In Python, how can you do this if you want a class to create only one instance object?

Ideas: 1. Different objects created from the same class are directed to the same direction.

2. Allow a class to create only unique instance objects.

Method: Use _ _new_ _ method

"Define a Class"

Let the class create an object by itself through the new method

And judge each time the object is created, if the variable instance object is not created, point to the created singleton object

code example:

# Coding=utf-8
Class Carfactory (object):
"" Defines a car factory class "" "
__first_new = true # defines a variable first created as True
__instance = none # defines a variable singleton object without

def __new__ (CLS):
"" Defines a __new__ method "" "
If cls.__first_new: # if variable: first created as true
Cls.__instance = object.__new__ (CLS) # creates the current instance object Cls.__instance point to object.__new__ (CLS)
Cls.__first_new = False # Let him be false after creating an object
Return Cls.__instance # Returns the created instance object
Else
Return cls.__instance # If variable: first created as false returns the last strength object directly

Feng_tian = Carfactory ()
Da_zhong = Carfactory ()
Print (Feng_tian)
Print (Da_zhong)

Output:

Point to the same direction

Singleton mode "Python"

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.