Python对象cach

2024-05-17 05:05:09 发布

您现在位置: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'

这段代码有什么问题?为什么不行?有办法让它起作用吗?如果不是,我该如何轻松透明地对最终用户缓存对象进行操作?


Tags: 代码testselfnonecachereturniftitle
3条回答

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

如果要操作创建,则需要更改__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
>>> 

一旦创建了已创建对象的实例,就不能对其进行真正的更改。当将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)

相关问题 更多 >