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) # 私有属性不能直接访问

    结果:

  • 相关阅读:
    flexbox 伸缩布局盒
    border-radius 知识点
    appium+Python第一个unitest
    linux常用命令整理
    appium的demo编程
    appium+Python环境搭建
    pycharm将py文件打包成可执行文件exe
    jmeter线程组设置
    jmeter的如何设置headers
    Python使用pillow的坑
  • 原文地址:https://www.cnblogs.com/yszd/p/10088867.html
Copyright © 2011-2022 走看看