@classmethod question
Scott SA
pydev at rscorp.ab.ca
Tue Apr 29 16:30:08 EDT 2008
On 4/23/08, Ivan Illarionov (ivan.illarionov at gmail.com) wrote:
>On 24 ???, 07:27, Scott SA <py... at rscorp.ab.ca> wrote:
>> I'm using the @classemethod decorator for some convenience methods and for
>
>It would make sense to separate instance-level and class-level
>behaviour with additional 'objects' namespace. e.g.
>cookie_recipie.get_ingredients() to get ingredients only for cookie
>recipie and RecipieClass.objects.get_ingrendients([....]) to get all
>the ingredients.
As mentioned in another reply, my example was a poor representation of what I was tryin to ask.
With that said, your reply is amazingly helpful in my quest to understand python, Django, etc. Django is the ORM I referred to, so the material you have written helps explain a few things.
>The elegant solution (AFAIK used by Django) would be to use metaclass
>and the object with custom descriptor for class-object/table level
>stuff.
>
>Something like this:
>
>class RecipieMetaclass(type):
> def __new__(cls, bases, attrs):
> new_cls = type.__new__(cls, name, bases, attrs)
> new_cls.objects = IngredientsDescriptor(IngredientsManager())
> return new_cls
>
>class RecipieClass(object):
> __metaclass__ = RecipieMetaclass
> def get_ingredients(self, recipie_list=None):
> return self.do_something_interesting(recipie_list)
>
>class IngredientsManager(object):
> def get_ingredients(self, recipie_list=None):
> return do_something_boring(recipie_list)
>
>class IngredientsDescriptor(object):
> def __init__(self, ingredients_manager):
> self.ingredients_manager = ingredients_manager
> def __get__(self, instance, type=None):
> if instance is not None:
> raise AttributeError, "Access via %s instances is not
>allowed" % type.__name__
> return self.ingredients_manager
>
>Then, "at another time, wanting to know what all the ingredients would
>be to make cookies, cake and bread" you would call:
>RecipieClass.objects.get_ingrendients(['cookies','cake','bread'])
I'm a little vague on the interaction of the IngredientsDescrptor VS IngredientsManager. I gather the 'Descriptor' class is called via the __get__ which then does the instance check. Could this have been done in the 'Manager' class?
>Both Django and Google Apps Engine API use similar concepts and you
>can learn much more interesting looking in their source code.
I have been learning a lot from the Django code and other applications written within it. Still, some things just don't seem to gel, even after a host of google searches. I've not loked at the Google Apps stuff, but will follow your advice.
Thanks,
Scott
More information about the Python-list
mailing list