classmethod() not inherited?

Jack Diederich jack at performancedrivers.com
Thu Jan 16 20:49:20 CET 2003


On Thu, Jan 16, 2003 at 11:25:37AM +0100, Martin v. Löwis wrote:
> Jack Diederich <jack at performancedrivers.com> writes:
> 
> > How is it possible to have classmethods still be
> > classmethods in their kids?
> 
> As you found out, you have to explicitly generate class methods,
> again.
> 
> > I'd like to have ALL of the derivitives of Base
> > have foo as a classmethod, but it doesn't seem
> > to be automatic and the following doesn't work
> > 
> > import Test
> > 
> > for (Test.A .. Test.Z): # pseudo code
> >   Test.A.foo = classmethod(Test.A.foo)
> 
> This doesn't work because the classmethod builtin does not really
> accept method objects. It would work if you write either
> 
>   Test.A.foo = classmethod(Test.A.foo.im_func)
> 
> or
> 
>   Test.A.foo = classmethod(Test.A.__dict__['foo'])
> 
> I readily admit that both constructs are hacks that make unacceptable
> use of implementation details :-)

I tried this for fun, and Object/classobjec.c#PyMethod_New
likes to throw BadInternalCall exceptions. (668980 bug on sourceforge is
very similar)

> 
> However, you may reconsider your need to redefine the class method in
> every subclass. The whole point of class methods is that they get the
> class as argument, which, in many cases, can help to avoid
> redefinitions, e.g. in
> 
> class Person:
>   minage = 0
>   maxage = 100
>   def span(self):
>     return self.maxage-self.minage
>   span=classmethod(span)
> 
> class Child:
>   maxage = 18
> 
> class Adult:
>   minage = 18
> 
> Now, the .span method works fine for all three classes.
> 

Perfect, I'd forgotten that extra spiffyness of classmethod versus
staticmethod.

-jack





More information about the Python-list mailing list