Emulate @classmethod using decorator and descriptor

Gabriel Genellina gagsl-py at yahoo.com.ar
Tue Dec 12 14:27:50 EST 2006


On 12 dic, 08:46, "WaterWalk" <toolmas... at 163.com> 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__

Basically you're right. But note that @classmethod does some additional
work to keep the details: the function name is now "wrapped", no
docstring, no argument names, no defaults, wrong type...

>>> class Test2(object):
...     @EmuClassMethod
...     def t2(cls, arg1, arg2=2):
...         "t2 docstring"
...         print "I'm %s arg1=%s arg2=%s" % (cls.__name__, arg1, arg2)
...
>>> print Test2.t2
<function wrapped at 0x00AB30B0>
>>> print Test2.t2.func_name
wrapped
>>> print Test2.t2.__doc__
None
>>> print Test2.t2.func_defaults
None
>>> Test2.t2(100)
I'm Test2 arg1=100 arg2=2
>>> Test2.t2(arg1=100)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: wrapped() got an unexpected keyword argument 'arg1'

-- 
Gabriel Genellina




More information about the Python-list mailing list