Emulate @classmethod using decorator and descriptor

Dustan DustanGroups at gmail.com
Tue Dec 12 07:12:41 EST 2006


WaterWalk wrote:
> Hello, I was recently learning python decorator and descriptor and
> emulated a @classmethod decorator:
> class EmuClassMethod(object):
>     def __init__(self, f=None):
>         self.f = f
>     def __get__(self, obj, klass=None):
>         if klass is None:
>            klass = type(obj)
>         def  wrapped(*args):
>            return self.f(klass, *args)
>         return wrapped
>
> class Test(object):
>     @EmuClassMethod
>     def t(cls):
>         print "I'm %s" % cls.__name__
>
> It worked, and seems that a function decorator works as follows:
> # decf is a decorator
> @decf
> def func():
>     print 'func'
>
> will be "converted" to:
>
> def func():
>     print 'func'
> func = decf(func)
>
> Is this really the case? Or correct me if i'm wrong. Thanks in advance.

Yes, the two are equivalent. The documentation is found here:
http://docs.python.org/ref/function.html

But I personally found the explanation for decorators a bit confusing.




More information about the Python-list mailing list