Python面试题

当前位置: 面试问题网 > 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文档下载到电脑,方便收藏和打印

推荐程度:

进入下载页面
上一篇:什么是lambda函数 下一篇:Python面试题:Python是如何进行内存管理的

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

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

cls 单例模式 python
复制网址 收藏网址 分享到微信 分享到微博 分享到QQ

其它栏目

软件工程师面试题 软件测试面试题 网络管理员面试题 java面试题 .NET面试题 PHP面试题 C#面试题 C++面试题 Delphi面试题 Ruby面试题 Python面试题 Javascript面试题 android面试题 iOS面试题 jQuery面试题 Linux/Unix面试题 DBA面试题

也许您还喜欢