Python单例模式

 1 # -*- coding: utf-8 -*-
 2 """
 3 Created on Sat Dec  8 17:32:05 2018
 4 单例模式
 5 @author: zhen
 6 """
 7 """
 8     普通类
 9 """
10 class Man(object):
11     def __new__(cls, name):
12         return object.__new__(cls)
13         
14     def __init__(self, name):
15         self.name = name
16        
17 """
18     单例类
19 """
20 class Singleton_Pattern_Man(object):
21     __man = None  # 私有属性,只能类内直接访问
22     __flag = None
23     def __new__(cls, name):
24         if cls.__man == None:
25             cls.__man = object.__new__(cls)
26             return cls.__man
27         else:
28             return cls.__man  # 上一次创建的对象
29         
30     def __init__(self, name):
31         if Singleton_Pattern_Man.__flag == None: # name属性只赋值一次,防止出现歧义
32             self.name = name
33             Singleton_Pattern_Man.__flag = 1
34         
35 man = Man("吴京")
36 another_man = Man("杰克")
37 print(id(man), man.name)
38 print(id(another_man), another_man.name)
39 print("----------------------------------")
40 singleton_man = Singleton_Pattern_Man("吴京")
41 singleton_another_man = Singleton_Pattern_Man("杰克")
42 print(id(singleton_man), singleton_man.name)
43 print(id(singleton_another_man), singleton_another_man.name)
44 # print(Singleton_Pattern_Man.__man) # 私有属性不能直接访问

结果:

原文地址:https://www.cnblogs.com/yszd/p/10088867.html