栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python对象缓存

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python对象缓存

如果要操纵创作,则需要进行更改

__new__

>>> class Page(object):...     cache = []...     """ Return cached object """...     @classmethod...     def __getCache(cls, title):...         for o in Page.cache:...  if o.__searchTerm == title or o.title == title:...      return o...         return None...     """ Initilize the class and start processing """...     def __new__(cls, title, api=None):...         o = cls.__getCache(title)...         if o:...  return o...         page = super(Page, cls).__new__(cls)...         cls.cache.append(page)...         page.title = title...         page.api = api...         page.__searchTerm = title...         # ...etc...         return page... >>> a = Page('test')>>> b = Page('test')>>> >>> print a.title # workstest>>> print b.titletest>>> >>> assert a is b>>>

编辑: 使用

__init__

>>> class Page(object):...     cache = []...     @classmethod...     def __getCache(cls, title):...         """ Return cached object """...         for o in Page.cache:...  if o.__searchTerm == title or o.title == title:...      return o...         return None...     def __new__(cls, title, *args, **kwargs):...         """ Initilize the class and start processing """...         existing = cls.__getCache(title)...         if existing:...  return existing...         page = super(Page, cls).__new__(cls)...         return page...     def __init__(self, title, api=None):...         if self in self.cache:...  return...         self.cache.append(self)...         self.title = title...         self.api = api...         self.__searchTerm = title...         # ...etc... >>> >>> a = Page('test')>>> b = Page('test')>>> >>> print a.title # workstest>>> print b.titletest>>> assert a is b>>> assert a.cache is Page.cache>>>


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/645789.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号