Emulate @classmethod using decorator and descriptor

W

WaterWalk

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.
 
D

Dustan

WaterWalk said:
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.
 
G

Gabriel Genellina

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...
.... @EmuClassMethod
.... def t2(cls, arg1, arg2=2):
.... "t2 docstring"
.... print "I'm %s arg1=%s arg2=%s" % (cls.__name__, arg1, arg2)
....Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: wrapped() got an unexpected keyword argument 'arg1'
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top