Python object cache

后端 未结 3 2033
被撕碎了的回忆
被撕碎了的回忆 2020-12-17 01:09

I tried a bit of code but it seems to cause issues:

class Page:
    cache = []


    \"\"\" Return cached object \"\"\"
    def __getCache(self, title):
             


        
3条回答
  •  感情败类
    2020-12-17 01:47

    You cannot really change the instance of a created object once it has been created. When setting self to something else, all you do is change the reference that variable points to, so the actual object is not affected.

    This also explains why the title attribute is not there. You return as soon as you change the local self variable, preventing the current instance to get the title attribute initialized (not to mention that self at that point wouldn’t point to the right instance).

    So basically, you cannot change the object during its initialization (in __init__) as at that point it has already been created, and assigned to the variable. A constructor call like a = Page('test') is actually the same as:

    a = Page.__new__('test')
    a.__init__('test')
    

    So as you can see, the __new__ class constructor is called first, and that’s actually who’s responsible for creating the instance. So you could overwrite the class’ __new__ method to manipulate the object creation.

    A generally preferred way however is to create a simple factory method, like this:

    @classmethod
    def create (cls, title, api = None):
        o = cls.__getCache(title)
        if o:
            return o
        return cls(title, api)
    

提交回复
热议问题