如果要操纵创作,则需要进行更改
__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 # workstest>>> print b.titletest>>> >>> 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 # workstest>>> print b.titletest>>> assert a is b>>> assert a.cache is Page.cache>>>


