class SomeClass:
def hello(cls, name):
print "Hi there", cls, name
hello = classmethod(hello)
SomeClass.hello("Peter")
I've come across Thomas Heller's recipe in the online Python Cookbook,
but this would require SomeClass to be modified, and so fails my
criteria.
I've also come across Alex Martelli's recipe for emulating
staticmethod, but of course that doesn't deal with passing a class to
the wrapped method.
Hamish Lawson
Thomas
-----------
try:
object
except NameError:
class classmethod:
def __init__(self, func):
self.func = func
class _ClassMethod:
def __init__(self, cls, func):
self.cls = cls
self.func = func
def __call__(self, *args, **kw):
return self.func(self.cls, *args, **kw)
import ExtensionClass
object = ExtensionClass.Base
class object(ExtensionClass.Base):
def __class_init__(cls):
d = {}
for name, value in cls.__dict__.items():
if isinstance(value, classmethod):
d[name] = _ClassMethod(cls, value.func)
cls.__dict__.update(d)
#######
class SomeClass(object):
Cheers
Franz
"Hamish Lawson" <hamish...@yahoo.co.uk> schrieb im Newsbeitrag
news:915a998f.02060...@posting.google.com...
> There's a receipe about this in the ASPN, by Alex Martelli. Concise
> and effective. Strongly recommended.
If you are referring to recipe 52304 [1], then I am in fact using this
to emulate staticmethod() where needed - I agree that it's a concise and
effective implementaion of staticmethod(). But Alex's recipe doesn't
emulate classmethod(), since the class is not passed through to the
method (notwithstanding the fact that Alex uses the terms 'class method'
and 'static method' interchangeably in his accompanying discussion -
although he wrote that before Python 2.2 made the distinction). Hence
the reason I'm still looking for an emulation of classmethod().
[1] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52304
Hamish
> Here's the closest I came up with (you must rewrite your code to
> derive SomeClass from object, the rest can remain unchanged). ...
While ideally I was hoping not to have change any client code, your
solution is the next best thing in requiring only a minimal change and
in working with both Python 2.2's builtin classmethod() and with an
emulating wrapper. Thanks!
Hamish
I was astonished to see that classmethod() can be used in
classic classes, BTW.
Thomas