Class Methods Vs Any Other Callable

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Thu May 15 03:17:03 EDT 2008


vbgunz a écrit :
> I remember learning closures in Python and thought it was the dumbest
> idea ever. Why use a closure when Python is fully object oriented? I
> didn't grasp the power/reason for them until I started learning
> JavaScript and then BAM, I understood them.
> 
> Just a little while ago, I had a fear of decorators because I really
> couldn't find a definitive source to learn them (how to with with @).
> How important are they? They must be important otherwise why have'em
> in the language? I had to learn'em and then suddenly, BAM. I
> understand them.
> 
> My main issue with closures and decorators was hidden in the fact of
> how *dead simple* they were. All I needed were reasons to use them
> over doing it X style. So what is my point? How dead simple are class
> methods? 

Way dumber than closures and HOFs (which is what 'decorators' are when 
you take back the @syntactic sugar).

A classmethod is simply a method that works on the class itself - it 
takes the class as first argument, instead of taking the instance.

> I must be missing there point so I am convinced they must be
> dead simple.
> 
> classes, functions, instance and static methods are easy. So easy in
> fact, I could shoot myself in the foots without looking (preferably
> without aiming). So, why am I stuck on the *idea* of a class method?

Could it be because you don't see the implication of classes being 
objects too ?

> An instance method works on the instance
> A Static method is basically a function nested within a class object
> A class method is overkill?

Nope. It's sometimes pretty usefull.

> I can call a static or class method through either the class OR any
> instance of it. I've never designed a method that took advantage of
> the class name except in cases where I needed to extend a super class
> *but* even in this case, I didn't use the enclosing class name...

s/name//g

What you have is the class *object*, not the class name.

> Whats the deal with class methods, why use them over anything else?
> What does a class method accomplish in at least one line shorter than
> anything else? Does it help reduce duplication or typing? I am at a
> lost for words that can shed at least *one* good reason to use them.
 > What is the one greatest reason to use them?

Factory methods (alternate constructors...) is probably the most obvious 
use case. You need to get at the class to instanciate it, don't you ? An 
example of this pattern is dict.fromkeys().

You'll find a more elaborate example here too:
http://groups.google.fr/group/comp.lang.python/browse_frm/thread/65868e8a12bcf375/a31bb0e13bf09316#a31bb0e13bf09316

HTH



More information about the Python-list mailing list