我尝试了一些代码,但似乎会引起问题:
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'
这段代码有什么问题?为什么不行?有办法让它起作用吗?如果不是,我该如何轻松透明地对最终用户缓存对象进行操作?
self
是一个普通的局部变量,因此设置self = ..
只会将函数中的self
变量指向的值更改为。它不会改变实际的对象。见:Is it safe to replace a self object by another object of the same type in a method?
若要执行所需的操作,可以使用静态函数作为factory:
如果要操作创建,则需要更改
__new__
。编辑:使用
__init__
:一旦创建了已创建对象的实例,就不能对其进行真正的更改。当将
self
设置为其他值时,您所做的只是更改变量指向的引用,这样实际对象就不会受到影响。这也解释了为什么不存在
title
属性。只要更改本地self
变量,就会返回,从而阻止当前实例初始化title
属性(更不用说,此时的self
不会指向正确的实例)。因此,基本上,在初始化期间(在
__init__
)不能更改对象,因为此时该对象已经创建并分配给变量。像a = Page('test')
这样的构造函数调用实际上与:如您所见,首先调用
__new__
类构造函数,而实际上是谁负责创建实例。所以您可以覆盖类‘__new__
方法来操作对象创建。但是,通常首选的方法是创建一个简单的工厂方法,如下所示:
相关问题 更多 >
编程相关推荐