Class static methods

hellerthomas at my-deja.com hellerthomas at my-deja.com
Mon Jul 24 19:19:58 CEST 2000


In article <8lhlv5$6kl$1 at slb3.atl.mindspring.net>,
  aahz at netcom.com (Aahz Maruch) wrote:
> In article <8lh6ri$dkl$1 at nnrp1.deja.com>,
> Guillaume  <forums at memoire.com> wrote:
> >
> >Well, now that I have class static vars, I need class static
methods...
> >Is it possible in Python ? Not sure...
>
> Nope.  You have two options:
>
> * generate an instance of the class and fake it through an instance
> method (deprecated)
>
> * segregate the class into its own module and use module-global
> functions as proxies for class static methods (preferred)
This is probably good advise.

But if you really really need them, read on.

C:>python
Python 1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)] on win32
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> import ExtensionClass
>>>
>>> class ClassMethod:
...     def __init__ (self, klass, func):
...         self.im_self = klass
...         self.im_func = func
...     def __call__ (self, *args, **kw):
...         return apply (self.im_func, (self.im_self,) + args, kw)
...
>>>
>>> class ClassWithClassMethods (ExtensionClass.Base):
...     _class_methods_ = ()
...     def __class_init__ (self):
...         for name in self._class_methods_:
...             unbound = getattr (self, name)
...             func = getattr (self, name).im_func
...             method = ClassMethod (self, func)
...             setattr (self, name, method)
...
>>> class Test (ClassWithClassMethods):
...     _class_methods_ = ["classmethod"]
...     def method (self, *args, **kw):
...         print "method called with", self, args, kw
...     def classmethod (self, *args, **kw):
...         print "classmethod called with", self, args, kw
...
>>> class Test2 (Test):
...     pass
...
>>> Test.classmethod()
classmethod called with <extension class __main__.Test at 0083EF88> ()
{}
>>> Test2.classmethod()
classmethod called with <extension class __main__.Test2 at 00843820> ()
{}
>>>
>>> Test().classmethod()
classmethod called with <extension class __main__.Test at 0083EF88> ()
{}
>>> Test2().classmethod()
classmethod called with <extension class __main__.Test2 at 00843820> ()
{}
>>> Test().method()
method called with <Test instance at 00850348> () {}
>>> Test2().method()
method called with <Test2 instance at 00850348> () {}
>>>

Some notes:
You need Jim Fulton's ExtensionClass (included in Zope).
A subclass derived from ExtensionClass.Base calls __class_init__
immediately after the class is created.

Another possibility would be to use Metaclasses...

Regards

Thomas Heller


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list