classmethod() not inherited?
Martin v. Löwis
martin at v.loewis.de
Thu Jan 16 05:25:37 EST 2003
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 :-)
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.
HTH,
Martin
More information about the Python-list
mailing list