@classmethod question

Scott SA pydev at rscorp.ab.ca
Tue Apr 29 14:42:41 EDT 2008


On 4/24/08, Bruno Desthuilliers (bruno.42.desthuilliers at websiteburo.invalid) wrote:

>> It is a series of convenience methods, in this case I'm interacting
>> with a database via an ORM (object-relational model).
>
>out of curiosity : which one ?

I'm rapidly becoming a "django junkie"^TM

>> I want the ability
>> to call a class-ojbect and get related values, or pass some criteria and
>> get related values for them without collecting the records first as
>> instances, then iterating them. I need to call this from several places
>> so I want to be DRY (don't repeat yourself).
>> 
>> The easiest way to describe this as an analogy would be like having a
>> recipie for cookies and wanting to know all of the ingredients ahead of
>> time. Then, at another time, wanting to know what all the ingredients
>> would be to make cookies, cake and bread (i.e. complete shopping list).
>
>>   cookie_recipie = RecipieClass.get_recipie('cookies')
>>   cookie_recipie.get_ingredients()
>>         2C Flour
>>         0.5 C Sugar
>>         ...
>>         
>>   RecipieClass.get_ingrendients(['cookies','cake','bread'])
>>         8C Flour
>>         2C Sugar
>>         ...
>
> > Of course any suggestions on how this might be better approached 
>would > be interesting too.
>
>Why do you want the same method to do two different things ? You clearly 
>have two distincts methods doing different things here, and as a user of 

In retrospect, my example was poorer than I first thought - or was it my spec. Regardless, it wasn't quite right.

The question/premise should have been:

    Is there an effective/accptable way to include
    class-related utilities that are callable _without_
    instantiating an object?

I now get the feeling that some of what I was thinking of would be considered bad form and should be separated into the application or a library of sorts.

>  your code I'd find your API confusing. May I suggest a much simpler 
>approach:
>
>class Recipies(object):
>     @property
>     def ingredients(self):
>         return <dict of ingredient:qty for self>
>
>     @classmethod
>     def get_ingredients_for(cls, *id_recipies):
>         return <dict of ingredient:summed_qty for all id_recipies>
>
>print Recipie.get('cookie').ingredients
>print Recipies.get_ingredients_for('cookie', 'cake', 'bread')

Yes, thank you. While my example didn't accurately portray my original thoughts, this is an educational example of merit.

I'm still crossing the bridge of conceptual understanding into practical application. Decoration appears very useful, it's practical application requires a level of thought I'm not fluent. Google is helping.

>My 2 cents...

You're short-changing yourself ;-)

Thanks for your input,

Scott



More information about the Python-list mailing list