Python面试题

当前位置: 面试问题网 > Python面试题 > Python如何实现单例模式

Python如何实现单例模式

Python有两种方式可以实现单例模式,下面两个例子使用了不同的方式实现单例模式:
   1.
   class Singleton(type):
   def __init__(cls, name, bases, dict):
   super(Singleton, cls).__init__(name, bases, dict)
   cls.instance = None
  
   def __call__(cls, *args, **kw):
   if cls.instance is None:
   cls.instance = super(Singleton, cls).__call__(*args, **kw)
  
   return cls.instance
  
   class MyClass(object):
   __metaclass__ = Singleton
  
   print MyClass()
   print MyClass()
   2. 使用decorator来实现单例模式
   def singleton(cls):
   instances = {}
   def getinstance():
   if cls not in instances:
   instances[cls] = cls()
   return instances[cls]
   return getinstance
  
   @singleton
   class MyClass:
   …

【Python如何实现单例模式】相关文章

1. Python如何实现单例模式

2. Python面试题:如何用Python来发送邮件

3. Python面试题:Python里面如何生成随机数

4. Python面试题:Python是如何进行内存管理的

5. Python如何定义一个函数

6. Python里面如何实现tuple和list的转换

7. 请写出一段Python代码实现删除一个list里面的重复元素

8. 软件测试LoadRunner面试题:What is think time? How do you change the threshold?

9. Python里面如何拷贝一个对象

10. Python中如何定义一个函数

本文来源:https://www.mianshiwenti.com/a13506.html

点击展开全部

《Python如何实现单例模式》

将本文的Word文档下载到电脑,方便收藏和打印

推荐程度:

进入下载页面

﹝Python如何实现单例模式﹞相关内容

「Python如何实现单例模式」相关专题

其它栏目

也许您还喜欢