我嘗試了一些代碼,但它似乎會導致問題:Python對象緩存
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'
哪些錯誤與此位的代碼?爲什麼不行?有沒有辦法讓它工作?如果不是,我如何輕鬆,透明地向最終用戶緩存對象?
這很聰明,只是不使用'__init__' .. –
@BrendanLong,如果你有辦法找出什麼時候跳過它,你可以使用'__init__'。 – dnozay