zoukankan      html  css  js  c++  java
  • 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) # 私有属性不能直接访问

    结果:

  • 相关阅读:
    Tsql 获取服务器信息
    数据字典生成脚本 【转载】
    c# winform文本框数字,数值校验
    ReentrantLock和AbstractQueuedSynchronizer的分析
    多线程
    前缀和与差分数组
    链表
    堆(优先队列)
    排序算法
    二分查找(递归和非递归)
  • 原文地址:https://www.cnblogs.com/yszd/p/10088867.html
Copyright © 2011-2022 走看看