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"