Python对象缓存 [英] Python object cache
本文介绍了Python对象缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试了一些代码,但似乎会引起问题:
I tried a bit of code but it seems to cause issues:
class Page:
cache = []
""" Return cached object """
def __getCache(self, 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 __init__(self, title, api=None):
o = self.__getCache(title)
if o:
self = o
return
Page.cache.append(self)
# Other init code
self.__searchTerm = title
self.title = self.someFunction(title)
然后我尝试:
a = Page('test')
b = Page('test')
print a.title # works
print b.title # AttributeError: Page instance has no attribute 'title'
这段代码有什么问题?为什么不起作用?有办法使它起作用吗?如果不是这样,我该如何轻松,透明地向最终用户缓存对象?
Whats wrong with this bit of code? Why wont it work? Is there a way to make it work? If not how do I go about easily and transparently to the end user caching objects?
推荐答案
如果您要操纵创建的内容,您需要更改 __ new __
。
if you want to manipulate the creation, you need to change __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 # works
test
>>> print b.title
test
>>>
>>> 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 # works
test
>>> print b.title
test
>>> assert a is b
>>> assert a.cache is Page.cache
>>>
这篇关于Python对象缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文