2016年最新Python 面试题

匿名网友 匿名网友 发布于: 2016-11-25 00:00:00
阅读 153 收藏 0 点赞 0 评论 0

谈谈装饰器

Python的装饰器也是一个函数,不过是返回函数对象的高阶函数,可以让其他函数在不修改代码的情况下增加额外的功能。经常用于添加log,

时间性能测试,事务处理,缓存等。装饰器可以抽离与具体函数无关的相同代码并进行重用。

 

Python实现单例模式

1.使用装饰器实现

def singleton(cls, *arg, **kw):

instances = { }

def _singleton():

if cls not in instances:

instances[cls] = cls(*arg, **kw)

return instances[cls]

return _singleton

2.使用基类

class Singleton(object):

def __new__(cls, *args, **kw):

if not hasattr(cls, ‘_instance’):

cls._instance = super(Singleton, cls).__new__(cls, *args, **kw)

return cls._instance

class MyClass(Singleton)

3.使用元类

class Singleton(type):

def __call__(cls, *args, **kw):

if not hasattr(cls, ‘_instance’):

cls._instance = super(Singleton, cls).__call(cls, *args, **kw)

return cls._instance

class MyClass(object):

__metaclass__ = Singleton

评论列表
文章目录