Help Understanding weakref (lazyloader)

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Ripter

    Help Understanding weakref (lazyloader)

    I found this script at http://www.pygame.org/wiki/LazyImage...arent=CookBook
    And I can't quite figure out how it works. I was wondering if someone
    could clarify it for me.
    The Code is:

    import pygame
    import weakref

    class ResourceControl ler(object):
    def __init__(self, loader):
    self.__dict__.u pdate(dict(
    names = {},
    cache = weakref.WeakVal ueDictionary(),
    loader = loader
    ))

    def __setattr__(sel f, name, value):
    self.names[name] = value

    def __getattr__(sel f, name):
    try:
    img = self.cache[name]
    except KeyError:
    img = self.loader(sel f.names[name])
    self.cache[name] = img
    return img


    class ImageController (ResourceContro ller):
    def __init__(self):
    ResourceControl ler.__init__(se lf, pygame.image.lo ad)


    My question is why does the __setattr__ set the value to
    self.names[name] instead of self.cache[name]?
  • Ripter

    #2
    Re: Help Understanding weakref (lazyloader)

    On Sep 3, 10:46 pm, Ripter <Ripter...@gmai l.comwrote:
    I found this script athttp://www.pygame.org/wiki/LazyImageLoadin g?parent=CookBo ok
    And I can't quite figure out how it works. I was wondering if someone
    could clarify it for me.
    The Code is:
    >
    import pygame
    import weakref
    >
    class ResourceControl ler(object):
        def __init__(self, loader):
            self.__dict__.u pdate(dict(
                names = {},
                cache = weakref.WeakVal ueDictionary(),
                loader = loader
            ))
    >
        def __setattr__(sel f, name, value):
            self.names[name] = value
    >
        def __getattr__(sel f, name):
            try:
                img = self.cache[name]
            except KeyError:
                img = self.loader(sel f.names[name])
                self.cache[name] = img
            return img
    >
    class ImageController (ResourceContro ller):
        def __init__(self):
            ResourceControl ler.__init__(se lf, pygame.image.lo ad)
    >
    My question is why does the __setattr__ set the value to
    self.names[name] instead of self.cache[name]?
    I feel stupid, I figured it out. (Don't program while watching Back to
    the Future)
    The reason would be the 'lazy' part. self.names holds the file name,
    and when you get the property back (__getattr__) it checks to see if
    it already got the value or not, and uses the name to get the value if
    it hasn't already.

    Duh. Sorry.

    Comment

    Working...