Using class attributes

Arnaud Delobelle arnodel at googlemail.com
Thu Feb 18 07:39:08 EST 2010


Leo Breebaart <leo at lspace.org> writes:

> Arnaud Delobelle <arnodel at googlemail.com> writes:
>
>> Descriptors to the rescue :)
>> 
>> def read_body_from(filename):
>>     print "** loading content **"
>>     return "<content of '%s'>" % filename
>> 
>> # This is a kind of class property
>> class TemplateFilename(object):
>>     def __get__(self, obj, cls):
>>         return "%s.tmpl" % cls.__name__
>> 
>> # And this is a kind of cached class property
>> class TemplateBody(object):
>>     def __get__(self, obj, cls):
>>         try:
>>             return cls._body
>>         except AttributeError:
>>             cls._body = read_body_from(cls.template_filename)
>>             return cls._body
>> 
>> class Foo(object):
>>     template_filename = TemplateFilename()
>>     template_body = TemplateBody()
>> 
>> class FooA(Foo):
>>    pass
>> 
>> class FooB(Foo):
>>    pass
>
> Very enlightening, thanks!
>
> By the way, I completely agree with the other posters in this
> thread that intricate solutions such as this are likely to be
> overkill, especially since at this point I have no idea if the
> inefficiency of reading those templates multiple times would at
> all matter (frankly, I'd doubt it). But it's certainly been
> educational to learn about these techniques.

Writing programs is a great way to keep learning :)

> One observation: if I implement the descriptor solution as given
> above, the code works perfectly, but running the code through
> pychecker now causes an error, because that again causes an
> attempt to read from the non-existant base class template file
> "Foo.tmpl"...

As someone said before, you could just provide a dummy Foo.tmpl file.

-- 
Arnaud



More information about the Python-list mailing list