Python 对象缓存

标签 python caching python-2.7 python-2.x

我尝试了一些代码,但似乎会引起问题:

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'

这段代码有什么问题吗?为什么它不起作用?有办法让它发挥作用吗?如果不是,我如何轻松且透明地对最终用户缓存对象?

最佳答案

如果你想操作创建,你需要更改__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 对象缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13054250/

相关文章:

ios - 如何缓存来自 API 的响应以防止额外的调用?

Python 代码在 2.7 中有效,但在 3.5 中无效

Python 函数 : Error with overtime while creating a wage function

python - 由 n 人组成 r 组的最佳方法,但尽量减少重叠

python - 正确使用 PyTorch 的 non_blocking=True 进行数据预取

caching - Play Framework 缓存注释

apache - 如何在具有多个 IP 和域的专用服务器中设置 Varnish?

python - 为每个唯一的 id 收集 python 中 csv 的所有值

python-2.7 - 使用opencv+python计算汽车

python - 尽管 JVM 取得了进步,为什么 Jython 比 CPython 慢得多?