Google
 
Webnews.only-4-geeks.com
Interesting places
news.only-4-geeks.com Forum Index » Python

Help Understanding weakref (lazyloader)

 
Jump to:  
 
Ripter
PostPosted: Thu Sep 04, 2008 2:46 am    Post subject: Help Understanding weakref (lazyloader)
       
I found this script at LINK
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 ResourceController(object):
def __init__(self, loader):
self.__dict__.update(dict(
names = {},
cache = weakref.WeakValueDictionary(),
loader = loader
))

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

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


class ImageController(ResourceController):
def __init__(self):
ResourceController.__init__(self, pygame.image.load)


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

 
Ripter
PostPosted: Thu Sep 04, 2008 3:04 am    Post subject: Re: Help Understanding weakref (lazyloader)
       
On Sep 3, 10:46 pm, Ripter <Ripter...@gmail.com> wrote:
Quote:
I found this script LINK
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 ResourceController(object):
    def __init__(self, loader):
        self.__dict__.update(dict(
            names = {},
            cache = weakref.WeakValueDictionary(),
            loader = loader
        ))

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

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

class ImageController(ResourceController):
    def __init__(self):
        ResourceController.__init__(self, pygame.image.load)

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.
 

Page 1 of 1 .:.

Google
 
Webnews.only-4-geeks.com

Windows Update | C++ | C | PHP | JavaScript | Photoshop | Programming | Windows 2000 | Python | Windows XP | Object | Flash | Flash - ActionScript | Paint Shop Pro | Excel | PowerPoint | Access | Word | Windows 98 | Internet Explorer 6.0 | CorelDraw12 | Java | XML | asm x86 | Linux Mandrake | Linux RedHat | Outlook |  | news from newsgroups |_ | s

Web Templates

Awesome Website Templates ©

bingo online Catering apteka oprocentowanie lokat Parkiet Wrocław