我尝试了一些代码但似乎会导致问题:
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'
这段代码怎么了?为什么不工作?有没有办法让它发挥作用?如果不是,我如何轻松透明地对最终用户缓存对象?
答案 0 :(得分:6)
如果您想操纵创作,则需要更改__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
>>>
答案 1 :(得分:3)
创建对象后,无法真正更改创建对象的实例。将self
设置为其他内容时,您所做的只是更改变量指向的引用,因此实际对象不会受到影响。
这也解释了title
属性不存在的原因。您在更改本地self
变量后立即返回,从而阻止当前实例初始化title
属性(更不用说此时self
不会指向右侧实例)。
所以基本上,你不能在初始化期间(__init__
)更改对象,因为它已经创建并分配给变量。像a = Page('test')
这样的构造函数调用实际上与:
a = Page.__new__('test')
a.__init__('test')
正如您所看到的,首先调用__new__
类构造函数,而这实际上是谁负责创建实例。因此,您可以覆盖类“__new__
方法来操纵对象创建。
通常首选的方法是创建一个简单的工厂方法,如下所示:
@classmethod
def create (cls, title, api = None):
o = cls.__getCache(title)
if o:
return o
return cls(title, api)
答案 2 :(得分:0)
self
是一个普通的局部变量,因此设置self = ..
只会更改self
变量指向该函数中的内容。它不会改变实际的对象。
请参阅:Is it safe to replace a self object by another object of the same type in a method?
要做你想做的事,你可以使用静态函数作为factory:
class Page:
cache = []
""" Return cached object """
@staticmethod
def create(title):
for o in Page.cache:
if o.__searchTerm == title or o.title == title:
return o
return Page(title)
""" Initilize the class and start processing """
def __init__(self, title, api=None):
Page.cache.append(self)
# Other init code
self.__searchTerm = title
self.title = title
a = Page.create('test')
b = Page.create('test')
print a.title
print b.title