why is there no class (static) methods in Python ?

James_Althoff at i2.com James_Althoff at i2.com
Mon Jun 18 15:21:53 EDT 2001


In response to Richard Gruet's inquiry concerning the lack of class methods
in Python,
Michael Lunnay wrote:
>why do you need it as part of the class, if it is related to the class
just
>have it in the same module so you can do:
>
>import foo
>
>x = foo.foo()
>print foo.staticfunction()
>
>Michael

In discussions of class methods in Python (or the lack thereof) the
question of "What's wrong with just using a module function instead?"
inevitably comes up.  Often, a module method works just fine.  However, it
is NOT the case that module functions are equivalent to (true) class
methods (a la Smalltalk).  A module function -- acting as a "poor man's
substitute" for a class method -- has the same limitation that a function
has vis a vis an instance method.  Namely, it does not provide support for
a "virtual" mechanism/framework.  As an example, suppose we have

yourModule.yourFunction1 -- acting as a class method substitute for the
class yourModule.YourClass.

And suppose the implementation of yourModule.yourFunction1 makes a call to
yourModule.yourFunction2.

Now suppose I create myModule.MyClass.  MyModule.MyClass is a subclass of
yourModule.YourClass so I can reuse all of the instance methods defined for
yourModule.YourClass (and its superclasses).  I can override and change any
instance methods I inherit from yourModule.yourClass and I can add any more
that I need.  This is great; I reuse instead of reinventing!

Now suppose I want to reuse the (pseudo) class methods for
yourModule.YourClass.  In particular I notice that yourModule.yourFunction1
is exactly what I want, but I need to override yourModule.yourFunction2 in
order to adapt it for myModule.MyClass.  How can I do this (preferably
WITHOUT resorting to "black magic" and whilst preserving
"thread-safeness")?

I am stuck -- because module functions are NOT methods (in the sense that
they are not associated with an instance) and hence do not participate in a
"method lookup/override" mechanism.  So if I define my own
myModule.yourFunction2, it doesn't help.  And I can't reuse
yourModule.yourFunction1.  I have to reimplement the exact same code.  This
is not nice.

So true class methods -- methods invoked on class objects with inheritance
and override (a la Smalltalk) -- are good -- and far better than module
functions acting as a poor man's substitute therein -- mainly if you
consider code extensibility and reuse a good thing.

Jim





More information about the Python-list mailing list