Emulating classmethod in Python 2.1
Thomas Heller
theller at python.net
Thu Jun 6 13:24:23 EDT 2002
"Hamish Lawson" <hamish_lawson at yahoo.co.uk> wrote in message news:915a998f.0206060833.12ad76a8 at posting.google.com...
> Is it possible to define a 'classmethod' class or function for Python
> 2.1 that would effectively provide the functionality of Python 2.2's
> built-in classmethod function and have the same usage pattern? I'd
> like to be able run code like that below against both 2.2 (using its
> builtin classmethod function) and 2.1 (using some added-in wrapper).
>
> 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.
>
Here's the closest I came up with (you must rewrite your code to
derive SomeClass from object, the rest can remain unchanged).
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):
def hello(cls, name):
print "Hi there", cls, name
hello = classmethod(hello)
SomeClass.hello("Peter")
More information about the Python-list
mailing list