Classmethods are evil

Duncan Booth duncan.booth at invalid.invalid
Mon May 19 03:56:33 EDT 2008


Hans Nowak <zephyrfalcon!NO_SPAM!@gmail.com> wrote:

> The way I see it, a class method is really just sugar for a function
> operating on the class, living in the class namespace.  As such, they
> are basically redundant, and as you point out, they can always be
> replaced by a function outside the class (and in fact, this was what
> people did before they came along in 2.2).  Personally, I don't use
> them... but some people like them.  Different strokes, and all that...
> 

In exactly the same way you could claim that a method is just sugar for a 
function operating on the instance living in the instance namespace. As 
such, you might think that they too are basically redundant, but they 
aren't: with instance methods you get the ability to override the method in 
a subclass without the caller needing to know whether they are calling the 
original method or an overridden version.

With class methods you also get the ability to override the method in a 
subclass, and again the caller doesn't need to know or care which variant 
when they call it.

Say you have a class hierarchy with a from_keys() class method. If you want 
to construct a new Foo you might call Foo.from_keys() without caring 
whether the method is the original one defined in one of Foo's base classes 
or a modified version specific to a Foo. If you were using functions then 
you would need to define a new from_keys() function for every class in a 
hierarchy, or at least for every different implementation in the hierarchy 
and the caller would need to be careful to call the correct one. So we end 
up with functions from_keys_Foo_or_Baz(cls) and from_keys_Bar() which is an 
unmaintainable mess.

-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list