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
>>>
EDIT: using __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
>>>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…