zoukankan      html  css  js  c++  java
  • 飘逸的python

    方法一:装饰器

    利用“装饰器只会执行一次”这个特点

     1 def singleton(cls):
     2     instances = []# 为什么这里不直接为None,因为内部函数没法访问外部函数的非容器变量
     3     def getinstance(*args, **kwargs):
     4         if not instances:
     5             instances.append(cls(*args, **kwargs))
     6         return instances[0]
     7     return getinstance
     8 
     9 @singleton
    10 class Foo:
    11     a = 1
    12 
    13 f1 = Foo()
    14 f2 = Foo()
    15 print id(f1), id(f2)

    方法二:基类

    利用“类变量对所有对象唯一”,即cls._instance

    1 class Singleton(object):
    2     def __new__(cls, *args, **kwargs):
    3         if not hasattr(cls, '_instance'):
    4             cls._instance = object.__new__(cls, *args, **kwargs)
    5         return cls._instance
    6 
    7 class Foo(Singleton):
    8     a = 1

    方法三:metaclass

    利用“类变量对所有对象唯一”,即cls._instance

    1 class Singleton(type):
    2     def __call__(cls, *args, **kwargs):
    3         if not hasattr(cls, '_instance'):
    4             cls._instance = super(Singleton, cls).__call__(*args, **kwargs)
    5         return cls._instance
    6 
    7 class Foo():
    8     __metaclass__ = Singleton

    方法四:Borg模式

    利用“类变量对所有对象唯一”,即__share_state

    1 class Foo:
    2    __share_state = {}
    3    def __init__(self):
    4        self.__dict__ = self.__share_state

    方法五:利用import

    利用“模块只会被import一次”

    1 #在文件mysingleton中
    2 class Foo(object):
    3      pass
    4 
    5 f = Foo()

    然后在其它模块,from mysingleton import f 
    直接拿f当作单例的对象来用

     
     转自:http://blog.csdn.net/handsomekang/article/details/46672047
  • 相关阅读:
    Day 20 初识面向对象
    Day 16 常用模块
    Day 15 正则表达式 re模块
    D14 模块 导入模块 开发目录规范
    Day 13 迭代器,生成器,内置函数
    Day 12 递归,二分算法,推导式,匿名函数
    Day 11 闭包函数.装饰器
    D10 函数(二) 嵌套,命名空间作用域
    D09 函数(一) 返回值,参数
    Day 07 Day08 字符编码与文件处理
  • 原文地址:https://www.cnblogs.com/lpxblog/p/7267960.html
Copyright © 2011-2022 走看看