8

我尝试了一些代码,但似乎会导致问题:

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'

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

4

3 回答 3

10

如果你想操纵创作,你需要改变__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
>>> 
于 2012-10-24T17:31:01.933 回答
4

一旦创建对象,您就无法真正更改它的实例。当设置self为其他值时,您所做的只是更改变量指向的引用,因此实际对象不受影响。

这也解释了为什么该title属性不存在。更改局部self变量后立即返回,防止当前实例title初始化属性(更不用说self此时不会指向正确的实例)。

所以基本上,你不能在它的初始化(in __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)
于 2012-10-24T17:22:59.867 回答
1

self是一个普通的局部变量,所以设置self = ..只是改变了该函数self中变量指向的内容。它不会改变实际对象。

请参阅:在方法中用另一个相同类型的对象替换 self 对象是否安全?

为了做你想做的事,你可以使用一个静态函数作为工厂

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
于 2012-10-24T17:15:39.987 回答