我尝试了一些代码,但似乎会引起问题:
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/